Android开发---OkHttp简单封装

来源:互联网 发布:经济学书单 知乎 编辑:程序博客网 时间:2024/06/03 19:10

今天看到一篇关于okhttp简单封装的博文,特借鉴一下留作备用


OkHttp 分为同步和异步请求;请求方式常用的有 get和post两种方式,封装请求的大致步骤为:

1、首先 创建 一个mOkHttpClient = new OkHttpClient()对象;

2、构建Request请求对象(根据get和post不同的请求方式分别创建);

3、如果是 post请求还需要 构建 请求参数 Params,RequestBody requestBody = buildFormData(params);  builder.post(requestBody).build;;

4、进行网络异步请求 mOkHttpClient.newCall(request).enqueue(new Callback() {} ),如果是同步请求,则改为 Response response = mOkHttpClient.newCall(request).execute()进行  ;

具体实现就不细说了,直接上代码如下:

[html] view plain copy
  1. public class OkHttpManager {  
  2.   
  3.     private static OkHttpManager mOkHttpManager;  
  4.   
  5.     private OkHttpClient mOkHttpClient;  
  6.   
  7.     private Gson mGson;  
  8.   
  9.     private Handler handler;  
  10.   
  11.     private OkHttpManager() {  
  12.         mOkHttpClient = new OkHttpClient();  
  13.         mOkHttpClient.newBuilder().connectTimeout(10, TimeUnit.SECONDS).readTimeout(10, TimeUnit.SECONDS)  
  14.                 .writeTimeout(10, TimeUnit.SECONDS);  
  15.         mGson = new Gson();  
  16.         handler = new Handler(Looper.getMainLooper());  
  17.     }  
  18.   
  19.     //创建 单例模式(OkHttp官方建议如此操作)  
  20.     public static OkHttpManager getInstance() {  
  21.         if (mOkHttpManager == null) {  
  22.             mOkHttpManager = new OkHttpManager();  
  23.         }  
  24.         return mOkHttpManager;  
  25.     }  
  26.   
  27.     /***********************  
  28.      * 对外公布的可调方法  
  29.      ************************/  
  30.   
  31.     public void getRequest(String url, final BaseCallBack callBack) {  
  32.         Request request = buildRequest(url, null, HttpMethodType.GET);  
  33.         doRequest(request, callBack);  
  34.     }  
  35.   
  36.     public void postRequest(String url, final BaseCallBack callBack, Map<String, String> params) {  
  37.         Request request = buildRequest(url, params, HttpMethodType.POST);  
  38.         doRequest(request, callBack);  
  39.     }  
  40.   
  41.     public void postUploadSingleImage(String url, final BaseCallBack callback, File file, String fileKey, Map<String, String> params) {  
  42.         Param[] paramsArr = fromMapToParams(params);  
  43.   
  44.         try {  
  45.             postAsyn(url, callback, file, fileKey, paramsArr);  
  46.         } catch (IOException e) {  
  47.             e.printStackTrace();  
  48.         }  
  49.   
  50.     }  
  51.   
  52.     public void postUploadMoreImages(String url, final BaseCallBack callback, File[] files, String[] fileKeys, Map<String, String> params) {  
  53.         Param[] paramsArr = fromMapToParams(params);  
  54.   
  55.         try {  
  56.             postAsyn(url, callback, files, fileKeys, paramsArr);  
  57.         } catch (IOException e) {  
  58.             e.printStackTrace();  
  59.         }  
  60.   
  61.     }  
  62.   
  63.     /***********************  
  64.      * 对内方法  
  65.      ************************/  
  66.     //单个文件上传请求  不带参数  
  67.     private void postAsyn(String url, BaseCallBack callback, File file, String fileKey) throws IOException {  
  68.         Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, null);  
  69.         doRequest(request, callback);  
  70.     }  
  71.   
  72.     //单个文件上传请求 带参数  
  73.     private void postAsyn(String url, BaseCallBack callback, File file, String fileKey, Param... params) throws IOException {  
  74.         Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, params);  
  75.         doRequest(request, callback);  
  76.     }  
  77.   
  78.     //多个文件上传请求 带参数  
  79.     private void postAsyn(String url, BaseCallBack callback, File[] files, String[] fileKeys, Param... params) throws IOException {  
  80.         Request request = buildMultipartFormRequest(url, files, fileKeys, params);  
  81.         doRequest(request, callback);  
  82.     }  
  83.   
  84.     //异步下载文件  
  85.     public void asynDownloadFile(final String url, final String destFileDir, final BaseCallBack callBack) {  
  86.         final Request request = buildRequest(url, null, HttpMethodType.GET);  
  87.         callBack.OnRequestBefore(request);  //提示加载框  
  88.         mOkHttpClient.newCall(request).enqueue(new Callback() {  
  89.             @Override  
  90.             public void onFailure(Call call, IOException e) {  
  91.                 callBack.onFailure(call, e);  
  92.             }  
  93.   
  94.             @Override  
  95.             public void onResponse(Call call, Response response) throws IOException {  
  96. //                callBack.onResponse(response);  
  97.   
  98.                 InputStream is = null;  
  99.                 byte[] buf = new byte[1024*2];  
  100.                 final long fileLength = response.body().contentLength();  
  101.                 int len = 0;  
  102.                 long readLength = 0;  
  103.                 FileOutputStream fos = null;  
  104.                 try {  
  105.                     is = response.body().byteStream();  
  106.                     File file = new File(destFileDir, getFileName(url));  
  107.                     fos = new FileOutputStream(file);  
  108.                     while ((len = is.read(buf)) != -1) {  
  109.                         fos.write(buf, 0, len);  
  110.                         readLength += len;  
  111.                         int curProgress = (int) (((float) readLength / fileLength) * 100);  
  112.                         Log.e("lgz", "onResponse: >>>>>>>>>>>>>" + curProgress + ", readLength = " + readLength + "fileLength = " + fileLength);  
  113.                         callBack.inProgress(curProgress, fileLength, 0);  
  114.                     }  
  115.                     fos.flush();  
  116.                     //如果下载文件成功,第一个参数为文件的绝对路径  
  117.                     callBackSuccess(callBack, call, response, file.getAbsolutePath());  
  118.                 } catch (IOException e) {  
  119.                     callBackError(callBack, call, response.code());  
  120.                 } finally {  
  121.                     try {  
  122.                         if (is != null)  
  123.                             is.close();  
  124.                     } catch (IOException e) {  
  125.                     }  
  126.                     try {  
  127.                         if (fos != null)  
  128.                             fos.close();  
  129.                     } catch (IOException e) {  
  130.                     }  
  131.                 }  
  132.             }  
  133.         });  
  134.   
  135.   
  136.     }  
  137.   
  138.     //构造上传图片 Request  
  139.     private Request buildMultipartFormRequest(String url, File[] files, String[] fileKeys, Param[] params) {  
  140.         params = validateParam(params);  
  141.         MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);  
  142.         for (Param param : params) {  
  143.             builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""),  
  144.                     RequestBody.create(MediaType.parse("image/png"), param.value));  
  145.         }  
  146.         if (files != null) {  
  147.             RequestBody fileBody = null;  
  148.             for (int i = 0; i < files.length; i++) {  
  149.                 File file = files[i];  
  150.                 String fileName = file.getName();  
  151.                 fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);  
  152.                 //TODO 根据文件名设置contentType  
  153.                 builder.addPart(Headers.of("Content-Disposition",  
  154.                         "form-data; name=\"" + fileKeys[i] + "\"; filename=\"" + fileName + "\""),  
  155.                         fileBody);  
  156.             }  
  157.         }  
  158.   
  159.         RequestBody requestBody = builder.build();  
  160.         return new Request.Builder()  
  161.                 .url(url)  
  162.                 .post(requestBody)  
  163.                 .build();  
  164.     }  
  165.   
  166.     //Activity页面所有的请求以Activity对象作为tag,可以在onDestory()里面统一取消,this  
  167.     public void cancelTag(Object tag) {  
  168.         for (Call call : mOkHttpClient.dispatcher().queuedCalls()) {  
  169.             if (tag.equals(call.request().tag())) {  
  170.                 call.cancel();  
  171.             }  
  172.         }  
  173.         for (Call call : mOkHttpClient.dispatcher().runningCalls()) {  
  174.             if (tag.equals(call.request().tag())) {  
  175.                 call.cancel();  
  176.             }  
  177.         }  
  178.     }  
  179.   
  180.     private String guessMimeType(String path) {  
  181.         FileNameMap fileNameMap = URLConnection.getFileNameMap();  
  182.         String contentTypeFor = fileNameMap.getContentTypeFor(path);  
  183.         if (contentTypeFor == null) {  
  184.             contentTypeFor = "application/octet-stream";  
  185.         }  
  186.         return contentTypeFor;  
  187.     }  
  188.   
  189.     private String getFileName(String path) {  
  190.         int separatorIndex = path.lastIndexOf("/");  
  191.         return (separatorIndex < 0) ? path : path.substring(separatorIndex + 1, path.length());  
  192.     }  
  193.   
  194.     private Param[] fromMapToParams(Map<String, String> params) {  
  195.         if (params == null)  
  196.             return new Param[0];  
  197.         int size = params.size();  
  198.         Param[] res = new Param[size];  
  199.         Set<Map.Entry<String, String>> entries = params.entrySet();  
  200.         int i = 0;  
  201.         for (Map.Entry<String, String> entry : entries) {  
  202.             res[i++] = new Param(entry.getKey(), entry.getValue());  
  203.         }  
  204.         return res;  
  205.     }  
  206.   
  207.     //去进行网络 异步 请求  
  208.     private void doRequest(Request request, final BaseCallBack callBack) {  
  209.         callBack.OnRequestBefore(request);  
  210.         mOkHttpClient.newCall(request).enqueue(new Callback() {  
  211.             @Override  
  212.             public void onFailure(Call call, IOException e) {  
  213.                 callBack.onFailure(call, e);  
  214.             }  
  215.   
  216.             @Override  
  217.             public void onResponse(Call call, Response response) throws IOException {  
  218.                 callBack.onResponse(response);  
  219.                 String result = response.body().string();  
  220.                 if (response.isSuccessful()) {  
  221.   
  222.                     if (callBack.mType == String.class) {  
  223. //                        callBack.onSuccess(call, response, result);  
  224.                         callBackSuccess(callBack, call, response, result);  
  225.                     } else {  
  226.                         try {  
  227.                             Object object = mGson.fromJson(result, callBack.mType);//自动转化为 泛型对象  
  228. //                            callBack.onSuccess(call, response, object);  
  229.                             callBackSuccess(callBack, call, response, object);  
  230.                         } catch (JsonParseException e) {  
  231.                             //json解析错误时调用  
  232.                             callBack.onEror(call, response.code(), e);  
  233.                         }  
  234.   
  235.                     }  
  236.                 } else {  
  237.                     callBack.onEror(call, response.code(), null);  
  238.                 }  
  239.   
  240.             }  
  241.   
  242.         });  
  243.   
  244.   
  245.     }  
  246.   
  247.     //创建 Request对象  
  248.     private Request buildRequest(String url, Map<String, String> params, HttpMethodType methodType) {  
  249.   
  250.         Request.Builder builder = new Request.Builder();  
  251.         builder.url(url);  
  252.         if (methodType == HttpMethodType.GET) {  
  253.             builder.get();  
  254.         } else if (methodType == HttpMethodType.POST) {  
  255.             RequestBody requestBody = buildFormData(params);  
  256.             builder.post(requestBody);  
  257.         }  
  258.         return builder.build();  
  259.     }  
  260.   
  261.     //构建请求所需的参数表单  
  262.     private RequestBody buildFormData(Map<String, String> params) {  
  263.         FormBody.Builder builder = new FormBody.Builder();  
  264.         builder.add("platform", "android");  
  265.         builder.add("version", "1.0");  
  266.         builder.add("key", "123456");  
  267.         if (params != null) {  
  268.             for (Map.Entry<String, String> entry : params.entrySet()) {  
  269.                 builder.add(entry.getKey(), entry.getValue());  
  270.             }  
  271.         }  
  272.         return builder.build();  
  273.     }  
  274.   
  275.     private void callBackSuccess(final BaseCallBack callBack, final Call call, final Response response, final Object object) {  
  276.         handler.post(new Runnable() {  
  277.             @Override  
  278.             public void run() {  
  279.                 callBack.onSuccess(call, response, object);  
  280.             }  
  281.         });  
  282.   
  283.     }  
  284.   
  285.     private void callBackError(final BaseCallBack callBack, final Call call, final int code) {  
  286.         handler.post(new Runnable() {  
  287.             @Override  
  288.             public void run() {  
  289.                 callBack.onEror(call, code, null);  
  290.             }  
  291.         });  
  292.   
  293.     }  
  294.   
  295.     private Param[] validateParam(Param[] params) {  
  296.         if (params == null)  
  297.             return new Param[0];  
  298.         else  
  299.             return params;  
  300.     }  
  301.   
  302.     public static class Param {  
  303.         public Param() {  
  304.         }  
  305.   
  306.         public Param(String key, String value) {  
  307.             this.key = key;  
  308.             this.value = value;  
  309.         }  
  310.   
  311.         String key;  
  312.         String value;  
  313.     }  
  314.   
  315.     enum HttpMethodType {  
  316.         GET, POST  
  317.     }  
  318.   
  319.   
  320. }  
其中的 BaseCallBack回调机制封装如下:

[java] view plain copy
  1. public abstract class BaseCallBack<T> {  
  2.     public Type mType;  
  3.   
  4.     static Type getSuperclassTypeParameter(Class<?> subclass) {  
  5.         Type superclass = subclass.getGenericSuperclass();  
  6.         if (superclass instanceof Class) {  
  7.             throw new RuntimeException("Missing type parameter.");  
  8.         }  
  9.         ParameterizedType parameterized = (ParameterizedType) superclass;  
  10.         return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);  
  11.     }  
  12.   
  13.   
  14.     public BaseCallBack() {  
  15.         mType = getSuperclassTypeParameter(getClass());  
  16.     }  
  17.   
  18.     protected abstract void OnRequestBefore(Request request);  
  19.   
  20.     protected abstract void onFailure(Call call, IOException e);  
  21.   
  22.     protected abstract void onSuccess(Call call, Response response, T t);  
  23.   
  24.     protected abstract void onResponse(Response response);  
  25.   
  26.     protected abstract void onEror(Call call, int statusCode, Exception e);  
  27.   
  28.     protected abstract void inProgress(int progress, long total , int id);  
  29. }  

上面这个类OkHttpManager 是我根据网络上各家资源学习封装好的,copy进代码可以直接使用,并且根据okhttp3.0以后的版本,对之前的一下请求参数设置进行了最新的修改,具体如下:

1、设置请求超时参数;     

okhttp3.0以前的版本是这样设置的 

new OkHttpClient(); 

mHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);

mHttpClient.setReadTimeout(10,TimeUnit.SECONDS);

  mHttpClient.setWriteTimeout(30,TimeUnit.SECONDS);

之后的版本是这样设置的:

new OkHttpClient.Builder()  
         .readTimeout(READ_TIMEOUT,TimeUnit.SECONDS)//设置读取超时时间  
         .writeTimeout(WRITE_TIMEOUT,TimeUnit.SECONDS)//设置写的超时时间  
          .connectTimeout(CONNECT_TIMEOUT,TimeUnit.SECONDS)//设置连接超时时间 

2、post方式请求时,构建表单对象参数;

okhttp3.0以前的版本是这样构建的:new  FormEncodingBuilder()对象,然后向里面add (key,value)参数;

之后的版本更改为:FormBody body = new FormBody.Builder(),.add(key, value);即是FormEncodingBuilder已被FormBody取代;

至于BaseCallBack类,根据请求数据的功能的不同,还需要对此进行封装,集成自己需要的方法实现;

一、进行一般的数据加载请求,可直接调用如下:

模拟用户登录:

[java] view plain copy
  1. Map<String, String> params = new HashMap<String, String>();  
  2.                    params.put("Mobile", username.getText().toString());  
  3.                    params.put("PassWord", password.getText().toString());  
  4.   
  5.                    OkHttpManager.getInstance().postRequest(Constants.LOGIN_URL, new LoadCallBack<String>(getActivity()) {  
  6.                                @Override  
  7.                                protected void onSuccess(Call call, Response response, String s) {  
  8.                                    Log.e("lgz""onSuccess = " + s);  
  9.                                    Toast.makeText(getActivity(), "登录成功!", Toast.LENGTH_LONG).show();  
  10.                                }  
  11.   
  12.                                @Override  
  13.                                protected void onEror(Call call, int statusCode, Exception e) {  
  14.                                    Log.e("lgz""Exception = " + e.toString());  
  15.                                }  
  16.                            }  
  17.                            , params);  

上面登录请求中 就用到了自己根据需要再次封装的Callback类的继承实现,LoadCallBack<T>类:

[java] view plain copy
  1. //添加对请求时对话框的处理  
  2. public abstract class LoadCallBack<T> extends BaseCallBack<T> {  
  3.     private Context context;  
  4.     private SpotsDialog spotsDialog;  
  5.   
  6.     public LoadCallBack(Context context) {  
  7.         this.context = context;  
  8.         spotsDialog = new SpotsDialog(context);  
  9.     }  
  10.   
  11.     private void showDialog() {  
  12.         spotsDialog.show();  
  13.     }  
  14.   
  15.     private void hideDialog() {  
  16.         if (spotsDialog != null) {  
  17.             spotsDialog.dismiss();  
  18.         }  
  19.     }  
  20.   
  21.     public void setMsg(String str) {  
  22.         spotsDialog.setMessage(str);  
  23.     }  
  24.   
  25.     public void setMsg(int  resId) {  
  26.         spotsDialog.setMessage(context.getString(resId));  
  27.     }  
  28.   
  29.   
  30.     @Override  
  31.     protected void OnRequestBefore(Request request) {  
  32.         showDialog();  
  33.   
  34.     }  
  35.   
  36.     @Override  
  37.     protected void onFailure(Call call, IOException e) {  
  38.         hideDialog();  
  39.     }  
  40.   
  41.     @Override  
  42.     protected void onResponse(Response response) {  
  43.         hideDialog();  
  44.     }  
  45.   
  46.     @Override  
  47.     protected void inProgress(int progress, long total, int id) {  
  48.   
  49.     }  
其实这个类就是对BaseCallBack再次继承实现;

二、下载文件,并显示进度条对话框的请求操作:

下载一张图片:

[java] view plain copy
  1. OkHttpManager.getInstance().asynDownloadFile("http://www.7mlzg.com/uploads/bwf_1477419976.jpg", FILE_PATH, new FileCallBack<String>(getActivity()) {  
  2.                     @Override  
  3.                     protected void onResponse(Response response) {  
  4.   
  5.                     }  
  6.   
  7.                     @Override  
  8.                     protected void onSuccess(Call call, Response response, String s) {  
  9.                         super.onSuccess(call, response, s);  
  10.                         Log.e("lgz""status = : " + s);  
  11.                         Toast.makeText(getActivity(), "下载成功", Toast.LENGTH_LONG).show();  
  12.                         Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);  
  13.                         Uri uri = Uri.fromFile(new File(s));//广播通知系统图集更新  
  14.                         intent.setData(uri);  
  15.                         getActivity().sendBroadcast(intent);  
  16.                     }  
  17.                 });  

上面下载图片中,就用到了自己根据需要再次继承Callback类封装得到的FileCallBack<T>类如下:

[java] view plain copy
  1. public abstract class FileCallBack<T> extends BaseCallBack<T> {  
  2.   
  3.     private Context mContext;  
  4.   
  5.     private ProgressDialog mProgressDialog;  
  6.   
  7.     public FileCallBack(Context context) {  
  8.         mContext = context;  
  9.         initDialog();  
  10.     }  
  11.   
  12.     private void initDialog(){  
  13.         mProgressDialog = new ProgressDialog(mContext);  
  14.         mProgressDialog.setTitle("下载中...");  
  15.         mProgressDialog.setCanceledOnTouchOutside(true);  
  16.         mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
  17.         mProgressDialog.setMax(100);  
  18.     }  
  19.   
  20.     private void hideDialog() {  
  21.         if (mProgressDialog != null) {  
  22.             mProgressDialog.dismiss();  
  23.         }  
  24.     }  
  25.   
  26.     @Override  
  27.     protected void OnRequestBefore(Request request) {  
  28.         mProgressDialog.show();  
  29.     }  
  30.   
  31.     @Override  
  32.     protected void onFailure(Call call, IOException e) {  
  33.        hideDialog();  
  34.     }  
  35.   
  36.     @Override  
  37.     protected void onSuccess(Call call, Response response, T t) {  
  38.         Log.e("lgz""onSuccess: >>>>>>>>>>>>>");  
  39.         hideDialog();  
  40.     }  
  41.   
  42.     @Override  
  43.     protected void onEror(Call call, int statusCode, Exception e) {  
  44.         hideDialog();  
  45.     }  
  46.   
  47.     @Override  
  48.     protected void inProgress(int progress, long total, int id) {  
  49.         Log.e("lgz""inProgress: >>>>>>>>>>>>>"+progress);  
  50.         mProgressDialog.setProgress(progress);  
  51.   
  52.     }  
  53. }  


三、最后说一下使用okhttp的配置:

在Android Studio 中,直接在build.gradle文件里配置 :compile 'com.squareup.okhttp3:okhttp:3.4.1'


原创粉丝点击