OKhttpManager2.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 * 当前类: OKhttp 工具封装类 20 * <p/> 21 * Created by ${火龙裸先生} on 2016/9/30. 22 * 邮箱:791335000@qq.com 23 */ 24 public class OkhttpManager2 { 25 26 private OkHttpClient client; 27 private static OkhttpManager2 okhttpManager2; 28 private Handler mHandler; 29 30 /** 31 * 单例模式 OKhttpManager2实例 32 */ 33 private static OkhttpManager2 getInstance() { 34 if (okhttpManager2 == null) { 35 okhttpManager2 = new OkhttpManager2(); 36 } 37 return okhttpManager2; 38 } 39 40 private OkhttpManager2() { 41 client = new OkHttpClient(); 42 mHandler = new Handler(Looper.getMainLooper()); 43 } 44 45 46 //****************** 内部逻辑处理方法 ******************/ 47 private Response p_getSync(String url) throws IOException { 48 Request request = new Request.Builder().url(url).build(); 49 Response response = client.newCall(request).execute(); 50 return response; 51 } 52 53 private String p_getSyncAsString(String url) throws IOException { 54 return p_getSync(url).body().string(); 55 } 56 57 private void p_getAsync(String url, final DataCallBack callBack) { 58 final Request request = new Request.Builder().url(url).build(); 59 client.newCall(request).enqueue(new Callback() { 60 @Override 61 public void onFailure(Call call, IOException e) { 62 deliverDataFailure(request, e, callBack); 63 } 64 65 @Override 66 public void onResponse(Call call, Response response) { 67 try { 68 String result = response.body().string(); 69 deliverDataSuccess(result, callBack); 70 } catch (IOException e) { 71 e.printStackTrace(); 72 deliverDataFailure(request, 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 if (params == null) { 81 params = new HashMap<String, String>(); 82 } 83 FormBody.Builder builder = new FormBody.Builder(); 84 for (Map.Entry<String, String> entry : params.entrySet()) { 85 String key = entry.getKey().toString(); 86 String value = null; 87 if (entry.getValue() == null) { 88 value = ""; 89 } else { 90 value = entry.getValue().toString(); 91 } 92 builder.add(key, value); 93 } 94 requestBody = builder.build(); 95 final Request request = new Request.Builder().url(url).post(requestBody).build(); 96 client.newCall(request).enqueue(new Callback() { 97 @Override 98 public void onFailure(Call call, IOException e) { 99 deliverDataFailure(request, e, callBack); 100 } 101 102 @Override 103 public void onResponse(Call call, Response response) throws IOException { 104 try { 105 String result = response.body().string(); 106 deliverDataSuccess(result, callBack); 107 } catch (IOException e) { 108 e.printStackTrace(); 109 deliverDataFailure(request, e, callBack); 110 } 111 } 112 }); 113 } 114 115 116 //****************** 数据分发的方法 ******************/ 117 private void deliverDataFailure(final Request request, final IOException e, final DataCallBack callBack) { 118 mHandler.post(new Runnable() {//发送到主线程 119 @Override 120 public void run() { 121 if (callBack != null) { 122 callBack.requestFailure(request, e); 123 } 124 } 125 }); 126 } 127 128 private void deliverDataSuccess(final String result, final DataCallBack callBack) { 129 mHandler.post(new Runnable() {//同样 发送到主线程 130 @Override 131 public void run() { 132 if (callBack != null) { 133 callBack.requestSuccess(result); 134 } 135 } 136 }); 137 } 138 139 140 //****************** 对外公布的方法 ******************/ 141 public static Response getSync(String url) throws IOException { 142 return getInstance().p_getSync(url);//同步GET,返回Response类型数据 143 } 144 145 public static String getSyncAsString(String url) throws IOException { 146 return getInstance().p_getSyncAsString(url);//同步GET,返回String类型数据(和上面getSync方法只是返回的数据类型不同而已) 147 } 148 149 public static void getAsync(String url, DataCallBack callBack) { 150 getInstance().p_getAsync(url, callBack);//异步GET 调用方法 151 } 152 153 public static void postAsync(String url, Map<String, String> params, DataCallBack callBack) { 154 getInstance().p_postAsync(url, params, callBack);//POST提交表单 调用方法 155 } 156 157 158 //****************** 数据回调接口 ******************/ 159 public interface DataCallBack { 160 void requestFailure(Request request, IOException e); 161 162 void requestSuccess(String result); 163 } 164 }
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.Request; 14 15 public class MainActivity extends AppCompatActivity implements View.OnClickListener { 16 17 private Button button1, button2, button3, button4; 18 private TextView textView; 19 20 @Override 21 protected void onCreate(Bundle savedInstanceState) { 22 super.onCreate(savedInstanceState); 23 setContentView(R.layout.activity_main); 24 button1 = (Button) findViewById(R.id.btn_one); 25 button2 = (Button) findViewById(R.id.btn_two); 26 button3 = (Button) findViewById(R.id.btn_three); 27 button4 = (Button) findViewById(R.id.btn_four); 28 button1.setOnClickListener(this); 29 button2.setOnClickListener(this); 30 button3.setOnClickListener(this); 31 button4.setOnClickListener(this); 32 textView = (TextView) findViewById(R.id.tv); 33 } 34 35 @Override 36 public void onClick(View view) { 37 switch (view.getId()) { 38 case R.id.btn_one://同步GET 39 new Thread(new Runnable() { 40 @Override 41 public void run() { 42 try { 43 // 调用getSync方法(以下两行),和调用getSyncAsString方法相同,只是返回数据类型不一样 44 // Response response = OkhttpManager2.getSync("http://cache.video.iqiyi.com/jp/avlist/202861101/1/?callback=jsonp9"); 45 // final String message = response.body().string(); 46 // 调用getSyncAsString方法(以下一行) 47 final String message = OkhttpManager2.getSyncAsString("http://cache.video.iqiyi.com/jp/avlist/202861101/1/?callback=jsonp9"); 48 runOnUiThread(new Runnable() { 49 @Override 50 public void run() { 51 textView.setText(message); 52 } 53 }); 54 } catch (IOException e) { 55 e.printStackTrace(); 56 } 57 } 58 }).start(); 59 break; 60 case R.id.btn_two://异步GET 61 OkhttpManager2.getAsync("http://web.juhe.cn:8080/finance/exchange/rmbquot", new OkhttpManager2.DataCallBack() { 62 @Override 63 public void requestFailure(Request request, IOException e) { 64 //数据加载成功会执行此方法,此时可以直接更新UI 65 textView.setText(e.toString()); 66 } 67 68 @Override 69 public void requestSuccess(String result) { 70 //数据加载成功会执行此方法,此时可以直接更新UI 71 textView.setText(result); 72 } 73 }); 74 break; 75 case R.id.btn_three://POST提交表单 76 Map<String, String> params = new HashMap<String, String>(); 77 params.put("cellphone", "123456");//用户名 78 params.put("password", "123456");//密码 79 OkhttpManager2.postAsync("http://58.250.31.19:28080/afeducation/appfront/main/loginUser_app.do", params, new OkhttpManager2.DataCallBack() { 80 @Override 81 public void requestFailure(Request request, IOException e) { 82 //数据加载成功会执行此方法,此时可以直接更新UI 83 textView.setText(e.toString()); 84 } 85 86 @Override 87 public void requestSuccess(String result) { 88 //数据加载成功会执行此方法,此时可以直接更新UI 89 textView.setText(result); 90 } 91 }); 92 break; 93 case R.id.btn_four://文件下载 94 95 break; 96 } 97 } 98 }
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 <Button 14 android:id="@+id/btn_one" 15 android:layout_width="wrap_content" 16 android:layout_height="wrap_content" 17 android:text="同步get" /> 18 19 <Button 20 android:id="@+id/btn_two" 21 android:layout_width="wrap_content" 22 android:layout_height="wrap_content" 23 android:text="异步get" /> 24 25 <Button 26 android:id="@+id/btn_three" 27 android:layout_width="wrap_content" 28 android:layout_height="wrap_content" 29 android:text="Post提交表单" /> 30 31 <Button 32 android:id="@+id/btn_four" 33 android:layout_width="wrap_content" 34 android:layout_height="wrap_content" 35 android:text="文件下载" /> 36 37 <TextView 38 android:id="@+id/tv" 39 android:layout_width="wrap_content" 40 android:layout_height="wrap_content" 41 android:text="text" /> 42 </LinearLayout>
个人觉得主要得注意的地方是,任何更新UI操作,都必须要在主线程中才能更新,而网络请求操作,则需要放在子线程。这里通过接口回调和数据分发的方式,利用Handler发送到主线程,实现UI的更新。