详解Android OkHttp完全解析

详解Android OkHttp完全解析,第1张

概述一、概述最近在群里听到各种讨论okhttp的话题,可见okhttp的口碑相当好了。再加上Google貌似在6.0版本里面删除了HttpClient相关API,对于这个行为不做评价。为了更好的在应对网络访问,学习下okhttp还是蛮必要的,本

一、概述

最近在群里听到各种讨论okhttp的话题,可见okhttp的口碑相当好了。再加上Google貌似在6.0版本里面删除了httpClIEnt相关API,对于这个行为不做评价。为了更好的在应对网络访问,学习下okhttp还是蛮必要的,本篇博客首先介绍okhttp的简单使用,主要包含:

一般的get请求 一般的post请求 基于http的文件上传 文件下载 加载图片 支持请求回调,直接返回对象、对象集合 支持session的保持

最后会对上述几个功能进行封装,完整的封装类的地址见:http://xiazai.jb51.net/201611/yuanma/okhttputils-master_jb51.zip

使用前,对于AndroID Studio的用户,可以选择添加:
compile 'com.squareup.okhttp:okhttp:2.4.0'
或者Eclipse的用户,可以下载最新的jarokhttp he latest JAR ,添加依赖就可以用了。

注意:okhttp内部依赖okio,别忘了同时导入okio:

gradle: compile 'com.squareup.okio:okio:1.5.0'

最新的jar地址:okio the latest JAR

二、使用教程

(一)http Get

对了网络加载库,那么最常见的肯定就是http get请求了,比如获取一个网页的内容。

//创建okhttpClIEnt对象OkhttpClIEnt mOkhttpClIEnt = new OkhttpClIEnt();//创建一个Requestfinal Request request = new Request.Builder()    .url("https://github.com/hongyangAndroID")    .build();//new callCall call = mOkhttpClIEnt.newCall(request); //请求加入调度call.enqueue(new Callback()  {   @OverrIDe   public voID onFailure(Request request,IOException e)   {   }   @OverrIDe   public voID onResponse(final Response response) throws IOException   {     //String HTMLStr = response.body().string();   }  });   

1.以上就是发送一个get请求的步骤,首先构造一个Request对象,参数最起码有个url,当然你可以通过Request.Builder设置更多的参数比如:header、method等。

2.然后通过request的对象去构造得到一个Call对象,类似于将你的请求封装成了任务,既然是任务,就会有execute()和cancel()等方法。

3.最后,我们希望以异步的方式去执行请求,所以我们调用的是call.enqueue,将call加入调度队列,然后等待任务执行完成,我们在Callback中即可得到结果。

看到这,你会发现,整体的写法还是比较长的,所以封装肯定是要做的,不然每个请求这么写,得累死。

ok,需要注意几点:

1、onResponse回调的参数是response,一般情况下,比如我们希望获得返回的字符串,可以通过response.body().string()获取;如果希望获得返回的二进制字节数组,则调用response.body().bytes();如果你想拿到返回的inputStream,则调用response.body().byteStream()

看到这,你可能会奇怪,竟然还能拿到返回的inputStream,看到这个最起码能意识到一点,这里支持大文件下载,有inputStream我们就可以通过IO的方式写文件。不过也说明一个问题,这个onResponse执行的线程并不是UI线程。的确是的,如果你希望 *** 作控件,还是需要使用handler等,例如:

@OverrIDepublic voID onResponse(final Response response) throws IOException{  final String res = response.body().string();  runOnUiThread(new Runnable()  {   @OverrIDe   public voID run()   {   mTv.setText(res);   }  });}

2、我们这里是异步的方式去执行,当然也支持阻塞的方式,上面我们也说了Call有一个execute()方法,你也可以直接调用call.execute()通过返回一个Response。

--------------------------------------------------------------------------------

(二) http Post 携带参数

看来上面的简单的get请求,基本上整个的用法也就掌握了,比如post携带参数,也仅仅是Request的构造的不同。

Request request = buildMultipartFormRequest(  url,new file[]{file},new String[]{fileKey},null);FormEnCodingBuilder builder = new FormEnCodingBuilder(); builder.add("username","张鸿洋");Request request = new Request.Builder()     .url(url)    .post(builder.build())    .build(); mOkhttpClIEnt.newCall(request).enqueue(new Callback(){});

大家都清楚,post的时候,参数是包含在请求体中的;所以我们通过FormEnCodingBuilder。添加多个String键值对,然后去构造Requestbody,最后完成我们Request的构造。

后面的就和上面一样了。

--------------------------------------------------------------------------------

(三)基于http的文件上传

接下来我们在介绍一个可以构造Requestbody的Builder,叫做MultipartBuilder。当我们需要做类似于表单上传的时候,就可以使用它来构造我们的requestbody。

file file = new file(Environment.getExternalStorageDirectory(),"balabala.mp4");Requestbody fileBody = Requestbody.create(MediaType.parse("application/octet-stream"),file);Requestbody requestbody = new MultipartBuilder()  .type(MultipartBuilder.FORM)  .addPart(headers.of(   "Content-disposition","form-data; name=\"username\""),Requestbody.create(null,"张鸿洋"))  .addPart(headers.of(   "Content-disposition","form-data; name=\"mfile\";    filename=\"wjd.mp4\""),fileBody)  .build();Request request = new Request.Builder() .url("http://192.168.1.103:8080/okhttpServer/fileUpload") .post(requestbody) .build();Call call = mOkhttpClIEnt.newCall(request);call.enqueue(new Callback(){ //...});

上述代码向服务器传递了一个键值对username:张鸿洋和一个文件。我们通过MultipartBuilder的addPart方法可以添加键值对或者文件。

其实类似于我们拼接模拟浏览器行为的方式,如果你对这块不了解,可以参考:从原理角度解析AndroID (Java) http 文件上传

ok,对于我们最开始的目录还剩下图片下载,文件下载;这两个一个是通过回调的Response拿到byte[]然后decode成图片;文件下载,就是拿到inputStream做写文件 *** 作,我们这里就不赘述了。

接下来我们主要看如何封装上述的代码。

--------------------------------------------------------------------------------

三、封装

由于按照上述的代码,写多个请求肯定包含大量的重复代码,所以我希望封装后的代码调用是这样的:

(一)使用

1.一般的get请求

OkhttpClIEntManager.getAsyn("https://www.baIDu.com",new OkhttpClIEntManager.ResultCallback<String>()  {   @OverrIDe   public voID onError(Request request,Exception e)   {    e.printstacktrace();   }   @OverrIDe   public voID onResponse(String u)   {    mTv.setText(u);//注意这里是UI线程   }  });

对于一般的请求,我们希望给个url,然后CallBack里面直接 *** 作控件。

2.文件上传且携带参数

我们希望提供一个方法,传入url,params,file,callback即可。

 OkhttpClIEntManager.postAsyn("http://192.168.1.103:8080/okhttpServer/fileUpload",// new OkhttpClIEntManager.ResultCallback<String>() {  @OverrIDe  public voID onError(Request request,IOException e)  {   e.printstacktrace();  }  @OverrIDe  public voID onResponse(String result)  {  } },// file,// "mfile",// new OkhttpClIEntManager.Param[]{   new OkhttpClIEntManager.Param("username","zhy"),new OkhttpClIEntManager.Param("password","123")}  );

键值对没什么说的,参数3为file,参数4为file对应的name,这个name不是文件的名字;
 对应于http中的

<input type="file" name="mfile" > 

对应的是name后面的值,即mfile.

3.文件下载

对于文件下载,提供url,目标dir,callback即可。

OkhttpClIEntManager.downloadAsyn( "http://192.168.1.103:8080/okhttpServer/files/messenger_01.png",Environment.getExternalStorageDirectory().getabsolutePath(),new OkhttpClIEntManager.ResultCallback<String>() {  @OverrIDe  public voID onError(Request request,IOException e)  {  }  @OverrIDe  public voID onResponse(String response)  {   //文件下载成功,这里回调的reponse为文件的absolutePath  }});

4.展示图片

展示图片,我们希望提供一个url和一个imagevIEw,如果下载成功,直接帮我们设置上即可。

OkhttpClIEntManager.displayImage(mImageVIEw,http://images.csdn.net/20150817/1.jpg);

内部会自动根据imagevIEw的大小自动对图片进行合适的压缩。虽然,这里可能不适合一次性加载大量图片的场景,但是对于app中偶尔有几个图片的加载,还是可用的。

四、整合Json

很多人提出项目中使用时,服务端返回的是Json字符串,希望客户端回调可以直接拿到对象,于是整合进入了Json,完善该功能。

(一)直接回调对象

例如现在有个User实体类:

package com.zhy.utils.http.okhttp;public class User { public String username ;  public String password ; public User() {  // Todo auto-generated constructor stub } public User(String username,String password) {  this.username = username;  this.password = password; } @OverrIDe public String toString() {  return "User{" +    "username='" + username + '\'' +    ",password='" + password + '\'' +    '}'; }}

服务端返回:

{"username":"zhy","password":"123"}

客户端可以如下方式调用:

 OkhttpClIEntManager.getAsyn("http://192.168.56.1:8080/okhttpServer/user!getUser",new OkhttpClIEntManager.ResultCallback<User>(){ @OverrIDe public voID onError(Request request,Exception e) {  e.printstacktrace(); } @OverrIDe public voID onResponse(User user) {  mTv.setText(u.toString());//UI线程 }});

我们传入泛型User,在onResponse里面直接回调User对象。 

 这里特别要注意的事,如果在Json字符串->实体对象过程中发生错误,程序不会崩溃,onError方法会被回调。

注意:这里做了少许的更新,接口命名从StringCallback修改为ResultCallback。接口中的onFailure方法修改为onError。

(二) 回调对象集合

依然是上述的User类,服务端返回

[{"username":"zhy","password":"123"},{"username":"lmj","password":"12345"}]

则客户端可以如下调用:

OkhttpClIEntManager.getAsyn("http://192.168.56.1:8080/okhttpServer/user!getUsers",new OkhttpClIEntManager.ResultCallback<List<User>>(){ @OverrIDe public voID onError(Request request,Exception e) {  e.printstacktrace(); } @OverrIDe public voID onResponse(List<User> us) {  Log.e("TAG",us.size() + "");  mTv.setText(us.get(1).toString()); }});

唯一的区别,就是泛型变为List<User> ,ok , 如果发现BUG或者有任何意见欢迎留言。

--------------------------------------------------------------------------------

源码

ok,基本介绍完了,对于封装的代码其实也很简单,我就直接贴出来了,因为也没什么好介绍的,如果你看完上面的用法,肯定可以看懂:

package com.zhy.utils.http.okhttp;import androID.graphics.Bitmap;import androID.graphics.BitmapFactory;import androID.os.Handler;import androID.os.Looper;import androID.Widget.ImageVIEw;import com.Google.gson.Gson;import com.Google.gson.internal.$Gson$Types;import com.squareup.okhttp.Call;import com.squareup.okhttp.Callback;import com.squareup.okhttp.FormEnCodingBuilder;import com.squareup.okhttp.headers;import com.squareup.okhttp.MediaType;import com.squareup.okhttp.MultipartBuilder;import com.squareup.okhttp.OkhttpClIEnt;import com.squareup.okhttp.Request;import com.squareup.okhttp.Requestbody;import com.squareup.okhttp.Response;import java.io.file;import java.io.fileOutputStream;import java.io.IOException;import java.io.inputStream;import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;import java.net.cookieManager;import java.net.cookiePolicy;import java.net.filenameMap;import java.net.URLConnection;import java.util.HashMap;import java.util.Map;import java.util.Set;/** * Created by zhy on 15/8/17. */public class OkhttpClIEntManager{ private static OkhttpClIEntManager mInstance; private OkhttpClIEnt mOkhttpClIEnt; private Handler mDelivery; private Gson mGson; private static final String TAG = "OkhttpClIEntManager"; private OkhttpClIEntManager() {  mOkhttpClIEnt = new OkhttpClIEnt();  //cookie enabled  mOkhttpClIEnt.setcookieHandler(new cookieManager(null,cookiePolicy.ACCEPT_ORIGINAL_SERVER));  mDelivery = new Handler(Looper.getMainLooper());  mGson = new Gson(); } public static OkhttpClIEntManager getInstance() {  if (mInstance == null)  {   synchronized (OkhttpClIEntManager.class)   {    if (mInstance == null)    {     mInstance = new OkhttpClIEntManager();    }   }  }  return mInstance; } /**  * 同步的Get请求  *  * @param url  * @return Response  */ private Response _getAsyn(String url) throws IOException {  final Request request = new Request.Builder()    .url(url)    .build();  Call call = mOkhttpClIEnt.newCall(request);  Response execute = call.execute();  return execute; } /**  * 同步的Get请求  *  * @param url  * @return 字符串  */ private String _getAsstring(String url) throws IOException {  Response execute = _getAsyn(url);  return execute.body().string(); } /**  * 异步的get请求  *  * @param url  * @param callback  */ private voID _getAsyn(String url,final ResultCallback callback) {  final Request request = new Request.Builder()    .url(url)    .build();  deliveryResult(callback,request); } /**  * 同步的Post请求  *  * @param url  * @param params post的参数  * @return  */ private Response _post(String url,Param... params) throws IOException {  Request request = buildPostRequest(url,params);  Response response = mOkhttpClIEnt.newCall(request).execute();  return response; } /**  * 同步的Post请求  *  * @param url  * @param params post的参数  * @return 字符串  */ private String _postAsstring(String url,Param... params) throws IOException {  Response response = _post(url,params);  return response.body().string(); } /**  * 异步的post请求  *  * @param url  * @param callback  * @param params  */ private voID _postAsyn(String url,final ResultCallback callback,Param... params) {  Request request = buildPostRequest(url,params);  deliveryResult(callback,request); } /**  * 异步的post请求  *  * @param url  * @param callback  * @param params  */ private voID _postAsyn(String url,Map<String,String> params) {  Param[] paramsArr = map2Params(params);  Request request = buildPostRequest(url,paramsArr);  deliveryResult(callback,request); } /**  * 同步基于post的文件上传  *  * @param params  * @return  */ private Response _post(String url,file[] files,String[] fileKeys,Param... params) throws IOException {  Request request = buildMultipartFormRequest(url,files,fileKeys,params);  return mOkhttpClIEnt.newCall(request).execute(); } private Response _post(String url,file file,String fileKey) throws IOException {  Request request = buildMultipartFormRequest(url,null);  return mOkhttpClIEnt.newCall(request).execute(); } private Response _post(String url,String fileKey,params);  return mOkhttpClIEnt.newCall(request).execute(); } /**  * 异步基于post的文件上传  *  * @param url  * @param callback  * @param files  * @param fileKeys  * @throws IOException  */ private voID _postAsyn(String url,ResultCallback callback,request); } /**  * 异步基于post的文件上传,单文件不带参数上传  *  * @param url  * @param callback  * @param file  * @param fileKey  * @throws IOException  */ private voID _postAsyn(String url,null);  deliveryResult(callback,request); } /**  * 异步基于post的文件上传,单文件且携带其他form参数上传  *  * @param url  * @param callback  * @param file  * @param fileKey  * @param params  * @throws IOException  */ private voID _postAsyn(String url,request); } /**  * 异步下载文件  *  * @param url  * @param destfileDir 本地文件存储的文件夹  * @param callback  */ private voID _downloadAsyn(final String url,final String destfileDir,final ResultCallback callback) {  final Request request = new Request.Builder()    .url(url)    .build();  final Call call = mOkhttpClIEnt.newCall(request);  call.enqueue(new Callback()  {   @OverrIDe   public voID onFailure(final Request request,final IOException e)   {    sendFailedStringCallback(request,e,callback);   }   @OverrIDe   public voID onResponse(Response response)   {    inputStream is = null;    byte[] buf = new byte[2048];    int len = 0;    fileOutputStream fos = null;    try    {     is = response.body().byteStream();     file file = new file(destfileDir,getfilename(url));     fos = new fileOutputStream(file);     while ((len = is.read(buf)) != -1)     {      fos.write(buf,len);     }     fos.flush();     //如果下载文件成功,第一个参数为文件的绝对路径     sendSuccessResultCallback(file.getabsolutePath(),callback);    } catch (IOException e)    {     sendFailedStringCallback(response.request(),callback);    } finally    {     try     {      if (is != null) is.close();     } catch (IOException e)     {     }     try     {      if (fos != null) fos.close();     } catch (IOException e)     {     }    }   }  }); } private String getfilename(String path) {  int separatorIndex = path.lastIndexOf("/");  return (separatorIndex < 0) ? path : path.substring(separatorIndex + 1,path.length()); } /**  * 加载图片  *  * @param vIEw  * @param url  * @throws IOException  */ private voID _displayImage(final ImageVIEw vIEw,final String url,final int errorResID) {  final Request request = new Request.Builder()    .url(url)    .build();  Call call = mOkhttpClIEnt.newCall(request);  call.enqueue(new Callback()  {   @OverrIDe   public voID onFailure(Request request,IOException e)   {    setErrorResID(vIEw,errorResID);   }   @OverrIDe   public voID onResponse(Response response)   {    inputStream is = null;    try    {     is = response.body().byteStream();     ImageUtils.ImageSize actualimageSize = ImageUtils.getimageSize(is);     ImageUtils.ImageSize imageVIEwSize = ImageUtils.getimageVIEwSize(vIEw);     int inSampleSize = ImageUtils.calculateInSampleSize(actualimageSize,imageVIEwSize);     try     {      is.reset();     } catch (IOException e)     {      response = _getAsyn(url);      is = response.body().byteStream();     }     BitmapFactory.Options ops = new BitmapFactory.Options();     ops.inJustDecodeBounds = false;     ops.inSampleSize = inSampleSize;     final Bitmap bm = BitmapFactory.decodeStream(is,null,ops);     mDelivery.post(new Runnable()     {      @OverrIDe      public voID run()      {       vIEw.setimageBitmap(bm);      }     });    } catch (Exception e)    {     setErrorResID(vIEw,errorResID);    } finally    {     if (is != null) try     {      is.close();     } catch (IOException e)     {      e.printstacktrace();     }    }   }  }); } private voID setErrorResID(final ImageVIEw vIEw,final int errorResID) {  mDelivery.post(new Runnable()  {   @OverrIDe   public voID run()   {    vIEw.setimageResource(errorResID);   }  }); } //*************对外公布的方法************ public static Response getAsyn(String url) throws IOException {  return getInstance()._getAsyn(url); } public static String getAsstring(String url) throws IOException {  return getInstance()._getAsstring(url); } public static voID getAsyn(String url,ResultCallback callback) {  getInstance()._getAsyn(url,callback); } public static Response post(String url,Param... params) throws IOException {  return getInstance()._post(url,params); } public static String postAsstring(String url,Param... params) throws IOException {  return getInstance()._postAsstring(url,params); } public static voID postAsyn(String url,Param... params) {  getInstance()._postAsyn(url,callback,params); } public static voID postAsyn(String url,String> params) {  getInstance()._postAsyn(url,params); } public static Response post(String url,params); } public static Response post(String url,String fileKey) throws IOException {  return getInstance()._post(url,fileKey); } public static Response post(String url,fileKey,Param... params) throws IOException {  getInstance()._postAsyn(url,String fileKey) throws IOException {  getInstance()._postAsyn(url,fileKey); } public static voID postAsyn(String url,params); } public static voID displayImage(final ImageVIEw vIEw,String url,int errorResID) throws IOException {  getInstance()._displayImage(vIEw,url,errorResID); } public static voID displayImage(final ImageVIEw vIEw,String url) {  getInstance()._displayImage(vIEw,-1); } public static voID downloadAsyn(String url,String destDir,ResultCallback callback) {  getInstance()._downloadAsyn(url,destDir,callback); } //**************************** private Request buildMultipartFormRequest(String url,Param[] params) {  params = valIDateParam(params);  MultipartBuilder builder = new MultipartBuilder()    .type(MultipartBuilder.FORM);  for (Param param : params)  {   builder.addPart(headers.of("Content-disposition","form-data; name=\"" + param.key + "\""),param.value));  }  if (files != null)  {   Requestbody fileBody = null;   for (int i = 0; i < files.length; i++)   {    file file = files[i];    String filename = file.getname();    fileBody = Requestbody.create(MediaType.parse(guessMimeType(filename)),file);    //Todo 根据文件名设置ContentType    builder.addPart(headers.of("Content-disposition","form-data; name=\"" + fileKeys[i] + "\"; filename=\"" + filename + "\""),fileBody);   }  }  Requestbody requestbody = builder.build();  return new Request.Builder()    .url(url)    .post(requestbody)    .build(); } private String guessMimeType(String path) {  filenameMap filenameMap = URLConnection.getfilenameMap();  String ContentTypeFor = filenameMap.getContentTypeFor(path);  if (ContentTypeFor == null)  {   ContentTypeFor = "application/octet-stream";  }  return ContentTypeFor; } private Param[] valIDateParam(Param[] params) {  if (params == null)   return new Param[0];  else return params; } private Param[] map2Params(Map<String,String> params) {  if (params == null) return new Param[0];  int size = params.size();  Param[] res = new Param[size];  Set<Map.Entry<String,String>> entrIEs = params.entrySet();  int i = 0;  for (Map.Entry<String,String> entry : entrIEs)  {   res[i++] = new Param(entry.getKey(),entry.getValue());  }  return res; } private static final String SESSION_KEY = "Set-cookie"; private static final String mSessionKey = "JsESSIONID"; private Map<String,String> mSessions = new HashMap<String,String>(); private voID deliveryResult(final ResultCallback callback,Request request) {  mOkhttpClIEnt.newCall(request).enqueue(new Callback()  {   @OverrIDe   public voID onFailure(final Request request,callback);   }   @OverrIDe   public voID onResponse(final Response response)   {    try    {     final String string = response.body().string();     if (callback.mType == String.class)     {      sendSuccessResultCallback(string,callback);     } else     {      Object o = mGson.fromJson(string,callback.mType);      sendSuccessResultCallback(o,callback);     }    } catch (IOException e)    {     sendFailedStringCallback(response.request(),callback);    } catch (com.Google.gson.JsonParseException e)//Json解析的错误    {     sendFailedStringCallback(response.request(),callback);    }   }  }); } private voID sendFailedStringCallback(final Request request,final Exception e,final ResultCallback callback) {  mDelivery.post(new Runnable()  {   @OverrIDe   public voID run()   {    if (callback != null)     callback.onError(request,e);   }  }); } private voID sendSuccessResultCallback(final Object object,final ResultCallback callback) {  mDelivery.post(new Runnable()  {   @OverrIDe   public voID run()   {    if (callback != null)    {     callback.onResponse(object);    }   }  }); } private Request buildPostRequest(String url,Param[] params) {  if (params == null)  {   params = new Param[0];  }  FormEnCodingBuilder builder = new FormEnCodingBuilder();  for (Param param : params)  {   builder.add(param.key,param.value);  }  Requestbody requestbody = builder.build();  return new Request.Builder()    .url(url)    .post(requestbody)    .build(); } public static abstract class ResultCallback<T> {  Type mType;  public ResultCallback()  {   mType = getSuperclasstypeParameter(getClass());  }  static Type getSuperclasstypeParameter(Class<?> subclass)  {   Type superclass = subclass.getGenericSuperclass();   if (superclass instanceof Class)   {    throw new RuntimeException("Missing type parameter.");   }   ParameterizedType parameterized = (ParameterizedType) superclass;   return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);  }  public abstract voID onError(Request request,Exception e);  public abstract voID onResponse(T response); } public static class Param {  public param()  {  }  public Param(String key,String value)  {   this.key = key;   this.value = value;  }  String key;  String value; }}

源码地址:demo下载http://xiazai.jb51.net/201611/yuanma/okhttputils-master_jb51.zip
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的详解Android OkHttp完全解析全部内容,希望文章能够帮你解决详解Android OkHttp完全解析所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1147595.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存