首页 > 代码库 > OKhttp的封装(上)
OKhttp的封装(上)
自从介绍了OKhttp3的一些基本使用之后,又偷了下懒,所以它的续篇被搁置了一段时间,现在补充。
OKhttpManager.Class 请求工具类
1 package com.example.administrator.okhttp3; 2 3 import android.os.Handler; 4 import android.os.Looper; 5 6 import java.io.IOException; 7 import java.util.HashMap; 8 import java.util.Map; 9 10 import okhttp3.Call; 11 import okhttp3.Callback; 12 import okhttp3.FormBody; 13 import okhttp3.OkHttpClient; 14 import okhttp3.Request; 15 import okhttp3.RequestBody; 16 import okhttp3.Response; 17 18 /** 19 * Created by ${火龙裸先生} on 2016/9/28. 20 * 邮箱:791335000@qq.com 21 * <p/> 22 * OKhttpManager OKhttp封装类 23 */ 24 public class OKhttpManager { 25 private OkHttpClient client; 26 private static OKhttpManager oKhttpManager; 27 private Handler mHandler; 28 29 /** 30 * 单例获取 OKhttpManager实例 31 */ 32 private static OKhttpManager getInstance() { 33 if (oKhttpManager == null) { 34 oKhttpManager = new OKhttpManager(); 35 } 36 return oKhttpManager; 37 } 38 39 private OKhttpManager() { 40 client = new OkHttpClient(); 41 mHandler = new Handler(Looper.getMainLooper()); 42 } 43 44 45 /************** 46 * 内部逻辑处理 47 ****************/ 48 private Response p_getSync(String url) throws IOException { 49 Request request = new Request.Builder().url(url).build(); 50 Response response = client.newCall(request).execute(); 51 return response; 52 } 53 54 private String p_getSyncAsString(String url) throws IOException { 55 return p_getSync(url).body().string(); 56 } 57 58 private void p_getAsync(String url, final DataCallBack callBack) { 59 final Request request = new Request.Builder().url(url).build(); 60 client.newCall(request).enqueue(new Callback() { 61 @Override 62 public void onFailure(Call call, IOException e) { 63 deliverDataFailure(call, e, callBack); 64 } 65 66 @Override 67 public void onResponse(Call call, Response response) { 68 try { 69 String result = response.body().string(); 70 deliverDataSuccess(result, callBack); 71 } catch (IOException e) { 72 deliverDataFailure(call, e, callBack); 73 } 74 } 75 }); 76 } 77 78 private void p_postAsync(String url, Map<String, String> params, final DataCallBack callBack) { 79 RequestBody requestBody = null; 80 81 if (params == null) { 82 params = new HashMap<String, String>(); 83 } 84 FormBody.Builder builder = new FormBody.Builder(); 85 for (Map.Entry<String, String> entry : params.entrySet()) { 86 String key = entry.getKey().toString(); 87 String value = http://www.mamicode.com/null; 88 if (entry.getValue() == null) { 89 valuehttp://www.mamicode.com/= ""; 90 } else { 91 value =http://www.mamicode.com/ entry.getValue().toString(); 92 } 93 builder.add(key, value); 94 } 95 requestBody = builder.build(); 96 final Request request = new Request.Builder().url(url).post(requestBody).build(); 97 client.newCall(request).enqueue(new Callback() { 98 @Override 99 public void onFailure(Call call, IOException e) {100 deliverDataFailure(call, e, callBack);101 }102 103 @Override104 public void onResponse(Call call, Response response) throws IOException {105 try {106 String result = response.body().string();107 deliverDataSuccess(result, callBack);108 } catch (IOException e) {109 deliverDataFailure(call, e, callBack);110 }111 }112 });113 }114 115 /**116 * 数据分发的方法117 */118 private void deliverDataFailure(final Call call, final IOException e, final DataCallBack callBack) {119 mHandler.post(new Runnable() {120 @Override121 public void run() {122 if (callBack != null) {123 callBack.requestFailure(call, e);124 }125 }126 });127 }128 129 private void deliverDataSuccess(final String result, final DataCallBack callBack) {130 mHandler.post(new Runnable() {131 @Override132 public void run() {133 if (callBack != null) {134 callBack.requestSuccess(result);135 }136 }137 });138 }139 140 141 /******************142 * 对外公布的方法143 *****************/144 public static Response getSync(String url) throws IOException {145 return getInstance().p_getSync(url);//同步GET,返回Response类型数据146 }147 148 149 public static String getSyncAsString(String url) throws IOException {150 return getInstance().p_getSyncAsString(url);//同步GET,返回String类型数据151 }152 153 public static void getAsync(String url, DataCallBack callBack) {154 getInstance().p_getAsync(url, callBack);//异步GET请求155 }156 157 public static void postAsync(String url, Map<String, String> params, DataCallBack callBack) {158 getInstance().p_postAsync(url, params, callBack);//异步POST请求159 }160 161 /**162 * 数据回调接口163 */164 public interface DataCallBack {165 void requestFailure(Call call, IOException e);166 167 void requestSuccess(String result);168 }169 170 }
MainActivity.class 工具类的调用方法
1 package com.example.administrator.okhttp3; 2 3 import android.os.Bundle; 4 import android.support.v7.app.AppCompatActivity; 5 import android.view.View; 6 import android.widget.Button; 7 import android.widget.TextView; 8 9 import java.io.IOException; 10 import java.util.HashMap; 11 import java.util.Map; 12 13 import okhttp3.Call; 14 import okhttp3.OkHttpClient; 15 import okhttp3.Request; 16 import okhttp3.Response; 17 18 public class MainActivity extends AppCompatActivity implements View.OnClickListener { 19 private static OkHttpClient client = new OkHttpClient(); 20 private Request request; 21 private Response response; 22 23 private Button button1, button2, button3, button4; 24 private TextView textView; 25 26 @Override 27 protected void onCreate(Bundle savedInstanceState) { 28 super.onCreate(savedInstanceState); 29 setContentView(R.layout.activity_main); 30 button1 = (Button) findViewById(R.id.btn_one); 31 button2 = (Button) findViewById(R.id.btn_two); 32 button3 = (Button) findViewById(R.id.btn_three); 33 button4 = (Button) findViewById(R.id.btn_four); 34 button1.setOnClickListener(this); 35 button2.setOnClickListener(this); 36 button3.setOnClickListener(this); 37 button4.setOnClickListener(this); 38 textView = (TextView) findViewById(R.id.tv); 39 } 40 41 @Override 42 public void onClick(View view) { 43 switch (view.getId()) { 44 case R.id.btn_one://同步GET 调用方法 45 46 new Thread(new Runnable() { 47 @Override 48 public void run() { 49 try { 50 final String message = OKhttpManager.getSyncAsString("http://cache.video.iqiyi.com/jp/avlist/202861101/1/?callback=jsonp9"); 51 runOnUiThread(new Runnable() { 52 @Override 53 public void run() { 54 textView.setText(message); 55 } 56 }); 57 } catch (IOException e) { 58 e.printStackTrace(); 59 } 60 } 61 }).start(); 62 63 break; 64 case R.id.btn_two://异步GET 调用方法 65 OKhttpManager.getAsync("http://web.juhe.cn:8080/finance/exchange/rmbquot", new OKhttpManager.DataCallBack() { 66 @Override 67 public void requestFailure(Call call, IOException e) { 68 /** 69 * 加载失败,回调这个方法 70 * */ 71 } 72 73 @Override 74 public void requestSuccess(String result) { 75 textView.setText(result); 76 } 77 }); 78 break; 79 case R.id.btn_three://POST提交表单 调用方法 80 Map<String, String> params = new HashMap<>(); 81 params.put("cellphone", "123456");//用户名 82 params.put("password", "123456");//密码 83 OKhttpManager.postAsync("http://58.250.31.19:28080/afeducation/appfront/main/loginUser_app.do", params, new OKhttpManager.DataCallBack() { 84 @Override 85 public void requestFailure(Call call, IOException e) { 86 textView.setText(e.toString()); 87 } 88 89 @Override 90 public void requestSuccess(String result) { 91 textView.setText(result); 92 } 93 }); 94 break; 95 case R.id.btn_four://文件下载 调用方法 96 97 break; 98 } 99 }100 }
activity_main.xml 布局文件
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:tools="http://schemas.android.com/tools" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:orientation="vertical" 7 android:paddingBottom="@dimen/activity_vertical_margin" 8 android:paddingLeft="@dimen/activity_horizontal_margin" 9 android:paddingRight="@dimen/activity_horizontal_margin"10 android:paddingTop="@dimen/activity_vertical_margin"11 tools:context="com.example.administrator.okhttp3.MainActivity">12 13 <Button14 android:id="@+id/btn_one"15 android:layout_width="wrap_content"16 android:layout_height="wrap_content"17 android:text="同步get" />18 19 <Button20 android:id="@+id/btn_two"21 android:layout_width="wrap_content"22 android:layout_height="wrap_content"23 android:text="异步get" />24 25 <Button26 android:id="@+id/btn_three"27 android:layout_width="wrap_content"28 android:layout_height="wrap_content"29 android:text="Post提交表单" />30 31 <Button32 android:id="@+id/btn_four"33 android:layout_width="wrap_content"34 android:layout_height="wrap_content"35 android:text="文件下载" />36 37 <TextView38 android:id="@+id/tv"39 android:layout_width="wrap_content"40 android:layout_height="wrap_content"41 android:text="text" />42 </LinearLayout>
以前都是用Volley去进行网络交互,时间久了,也想换换新的东西。网络请求框架各具特色,需要自己不断探索和选择。加油!
OKhttp的封装(上)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。