最近在群里听到各种讨论okhttp的话题,可见okhttp的口碑相当好了。再加上Google貌似在6.0版本里面删除了HttpClient相关API,对于这个行为不做评价。为了更好的在应对网络访问,学习下okhttp还是蛮必要的,本篇博客首先介绍okhttp的简单使用,主要包含:
最后会对上述几个功能进行封装,完整的封装类的地址见:https://github.com/hongyangAndroid/okhttp-utils
使用前,对于Android Studio的用户,可以选择添加:
<code class="language-xml hljs has-numbering">compile 'com.squareup.okhttp:okhttp:2.4.0'</code>
或者Eclipse的用户,可以下载最新的jar okhttp he latest JAR ,添加依赖就可以用了。
注意:okhttp内部依赖okio,别忘了同时导入okio:
gradle: compile 'com.squareup.okio:okio:1.5.0'
最新的jar地址:okio the latest JAR
对了网络加载库,那么最常见的肯定就是http get请求了,比如获取一个网页的内容。
<code class="language-java hljs has-numbering"><span class="hljs-comment">//创建okHttpClient对象</span> OkHttpClient mOkHttpClient = <span class="hljs-keyword">new</span> OkHttpClient(); <span class="hljs-comment">//创建一个Request</span> <span class="hljs-keyword">final</span> Request request = <span class="hljs-keyword">new</span> Request.Builder() .url(<span class="hljs-string">"https://github.com/hongyangAndroid"</span>) .build(); <span class="hljs-comment">//new call</span> Call call = mOkHttpClient.newCall(request); <span class="hljs-comment">//请求加入调度</span> call.enqueue(<span class="hljs-keyword">new</span> Callback() { <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onFailure</span>(Request request, IOException e) { } <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onResponse</span>(<span class="hljs-keyword">final</span> Response response) <span class="hljs-keyword">throws</span> IOException { <span class="hljs-comment">//String htmlStr = response.body().string();</span> } }); </code>
以上就是发送一个get请求的步骤,首先构造一个Request对象,参数最起码有个url,当然你可以通过Request.Builder设置更多的参数比如:header
、method
等。
然后通过request的对象去构造得到一个Call对象,类似于将你的请求封装成了任务,既然是任务,就会有execute()
和cancel()
等方法。
最后,我们希望以异步的方式去执行请求,所以我们调用的是call.enqueue,将call加入调度队列,然后等待任务执行完成,我们在Callback中即可得到结果。
看到这,你会发现,整体的写法还是比较长的,所以封装肯定是要做的,不然每个请求这么写,得累死。
ok,需要注意几点:
onResponse回调的参数是response,一般情况下,比如我们希望获得返回的字符串,可以通过response.body().string()
获取;如果希望获得返回的二进制字节数组,则调用response.body().bytes()
;如果你想拿到返回的inputStream,则调用response.body().byteStream()
看到这,你可能会奇怪,竟然还能拿到返回的inputStream,看到这个最起码能意识到一点,这里支持大文件下载,有inputStream我们就可以通过IO的方式写文件。不过也说明一个问题,这个onResponse
执行的线程并不是UI线程。的确是的,如果你希望操作控件,还是需要使用handler等,例如:
<code class="language-java hljs has-numbering"><span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onResponse</span>(<span class="hljs-keyword">final</span> Response response) <span class="hljs-keyword">throws</span> IOException { <span class="hljs-keyword">final</span> String res = response.body().string(); runOnUiThread(<span class="hljs-keyword">new</span> Runnable() { <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span>() { mTv.setText(res); } }); }</code>
execute()
方法,你也可以直接调用call.execute()
通过返回一个Response
。看来上面的简单的get请求,基本上整个的用法也就掌握了,比如post携带参数,也仅仅是Request的构造的不同。
<code class="language-java hljs has-numbering">Request request = buildMultipartFormRequest( url, <span class="hljs-keyword">new</span> File[]{file}, <span class="hljs-keyword">new</span> String[]{fileKey}, <span class="hljs-keyword">null</span>); FormEncodingBuilder builder = <span class="hljs-keyword">new</span> FormEncodingBuilder(); builder.add(<span class="hljs-string">"username"</span>,<span class="hljs-string">"张鸿洋"</span>); Request request = <span class="hljs-keyword">new</span> Request.Builder() .url(url) .post(builder.build()) .build(); mOkHttpClient.newCall(request).enqueue(<span class="hljs-keyword">new</span> Callback(){});</code>
大家都清楚,post的时候,参数是包含在请求体中的;所以我们通过FormEncodingBuilder。添加多个String键值对,然后去构造RequestBody,最后完成我们Request的构造。
后面的就和上面一样了。
接下来我们在介绍一个可以构造RequestBody的Builder,叫做MultipartBuilder
。当我们需要做类似于表单上传的时候,就可以使用它来构造我们的requestBody。
<code class="language-java hljs has-numbering">File file = <span class="hljs-keyword">new</span> File(Environment.getExternalStorageDirectory(), <span class="hljs-string">"balabala.mp4"</span>); RequestBody fileBody = RequestBody.create(MediaType.parse(<span class="hljs-string">"application/octet-stream"</span>), file); RequestBody requestBody = <span class="hljs-keyword">new</span> MultipartBuilder() .type(MultipartBuilder.FORM) .addPart(Headers.of( <span class="hljs-string">"Content-Disposition"</span>, <span class="hljs-string">"form-data; name=\"username\""</span>), RequestBody.create(<span class="hljs-keyword">null</span>, <span class="hljs-string">"张鸿洋"</span>)) .addPart(Headers.of( <span class="hljs-string">"Content-Disposition"</span>, <span class="hljs-string">"form-data; name=\"mFile\"; filename=\"wjd.mp4\""</span>), fileBody) .build(); Request request = <span class="hljs-keyword">new</span> Request.Builder() .url(<span class="hljs-string">"http://192.168.1.103:8080/okHttpServer/fileUpload"</span>) .post(requestBody) .build(); Call call = mOkHttpClient.newCall(request); call.enqueue(<span class="hljs-keyword">new</span> Callback() { <span class="hljs-comment">//...</span> });</code>
上述代码向服务器传递了一个键值对username:张鸿洋
和一个文件。我们通过MultipartBuilder的addPart方法可以添加键值对或者文件。
其实类似于我们拼接模拟浏览器行为的方式,如果你对这块不了解,可以参考:从原理角度解析Android (Java) http 文件上传
ok,对于我们最开始的目录还剩下图片下载,文件下载;这两个一个是通过回调的Response拿到byte[]然后decode成图片;文件下载,就是拿到inputStream做写文件操作,我们这里就不赘述了。
关于用法,也可以参考泡网OkHttp使用教程
接下来我们主要看如何封装上述的代码。
由于按照上述的代码,写多个请求肯定包含大量的重复代码,所以我希望封装后的代码调用是这样的:
一般的get请求
<code class="language-java hljs has-numbering"> OkHttpClientManager.getAsyn(<span class="hljs-string">"https://www.baidu.com"</span>, <span class="hljs-keyword">new</span> OkHttpClientManager.ResultCallback<String>() { <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onError</span>(Request request, Exception e) { e.printStackTrace(); } <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onResponse</span>(String u) { mTv.setText(u);<span class="hljs-comment">//注意这里是UI线程</span> } });</code>
对于一般的请求,我们希望给个url,然后CallBack里面直接操作控件。
文件上传且携带参数
我们希望提供一个方法,传入url,params,file,callback即可。
<code class="language-java hljs has-numbering"> OkHttpClientManager.postAsyn(<span class="hljs-string">"http://192.168.1.103:8080/okHttpServer/fileUpload"</span>,<span class="hljs-comment">//</span> <span class="hljs-keyword">new</span> OkHttpClientManager.ResultCallback<String>() { <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onError</span>(Request request, IOException e) { e.printStackTrace(); } <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onResponse</span>(String result) { } },<span class="hljs-comment">//</span> file,<span class="hljs-comment">//</span> <span class="hljs-string">"mFile"</span>,<span class="hljs-comment">//</span> <span class="hljs-keyword">new</span> OkHttpClientManager.Param[]{ <span class="hljs-keyword">new</span> OkHttpClientManager.Param(<span class="hljs-string">"username"</span>, <span class="hljs-string">"zhy"</span>), <span class="hljs-keyword">new</span> OkHttpClientManager.Param(<span class="hljs-string">"password"</span>, <span class="hljs-string">"123"</span>)} );</code>
键值对没什么说的,参数3为file,参数4为file对应的name,这个name不是文件的名字;
对应于http中的
<input type="file" name="mFile" >
对应的是name后面的值,即mFile.
文件下载
对于文件下载,提供url,目标dir,callback即可。
<code class="language-java hljs has-numbering">OkHttpClientManager.downloadAsyn( <span class="hljs-string">"http://192.168.1.103:8080/okHttpServer/files/messenger_01.png"</span>, Environment.getExternalStorageDirectory().getAbsolutePath(), <span class="hljs-keyword">new</span> OkHttpClientManager.ResultCallback<String>() { <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onError</span>(Request request, IOException e) { } <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onResponse</span>(String response) { <span class="hljs-comment">//文件下载成功,这里回调的reponse为文件的absolutePath</span> } });</code>
展示图片
展示图片,我们希望提供一个url和一个imageview,如果下载成功,直接帮我们设置上即可。
<code class="language-java hljs has-numbering"> OkHttpClientManager.displayImage(mImageView, <span class="hljs-string">"http://images.csdn.net/20150817/1.jpg"</span>);</code>
内部会自动根据imageview的大小自动对图片进行合适的压缩。虽然,这里可能不适合一次性加载大量图片的场景,但是对于app中偶尔有几个图片的加载,还是可用的。
很多人提出项目中使用时,服务端返回的是Json字符串,希望客户端回调可以直接拿到对象,于是整合进入了Gson,完善该功能。
例如现在有个User实体类:
<code class="language-java hljs has-numbering"><span class="hljs-keyword">package</span> com.zhy.utils.http.okhttp; <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> {</span> <span class="hljs-keyword">public</span> String username ; <span class="hljs-keyword">public</span> String password ; <span class="hljs-keyword">public</span> <span class="hljs-title">User</span>() { <span class="hljs-comment">// TODO Auto-generated constructor stub</span> } <span class="hljs-keyword">public</span> <span class="hljs-title">User</span>(String username, String password) { <span class="hljs-keyword">this</span>.username = username; <span class="hljs-keyword">this</span>.password = password; } <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span>() { <span class="hljs-keyword">return</span> <span class="hljs-string">"User{"</span> + <span class="hljs-string">"username='"</span> + username + <span class="hljs-string">'\''</span> + <span class="hljs-string">", password='"</span> + password + <span class="hljs-string">'\''</span> + <span class="hljs-string">'}'</span>; } }</code>
服务端返回:
<code class="language-xml hljs has-numbering">{"username":"zhy","password":"123"}</code>
客户端可以如下方式调用:
<code class="language-java hljs has-numbering"> OkHttpClientManager.getAsyn(<span class="hljs-string">"http://192.168.56.1:8080/okHttpServer/user!getUser"</span>, <span class="hljs-keyword">new</span> OkHttpClientManager.ResultCallback<User>() { <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onError</span>(Request request, Exception e) { e.printStackTrace(); } <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onResponse</span>(User user) { mTv.setText(u.toString());<span class="hljs-comment">//UI线程</span> } });</code>
我们传入泛型User,在onResponse里面直接回调User对象。
这里特别要注意的事,如果在json字符串->实体对象
过程中发生错误,程序不会崩溃,onError
方法会被回调。
注意:这里做了少许的更新,接口命名从StringCallback
修改为ResultCallback
。接口中的onFailure
方法修改为onError
。
依然是上述的User类,服务端返回
<code class="language-xml hljs has-numbering">[{"username":"zhy","password":"123"},{"username":"lmj","password":"12345"}]</code>
则客户端可以如下调用:
<code class="language-java hljs has-numbering">OkHttpClientManager.getAsyn(<span class="hljs-string">"http://192.168.56.1:8080/okHttpServer/user!getUsers"</span>, <span class="hljs-keyword">new</span> OkHttpClientManager.ResultCallback<List<User>>() { <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onError</span>(Request request, Exception e) { e.printStackTrace(); } <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onResponse</span>(List<User> us) { Log.e(<span class="hljs-string">"TAG"</span>, us.size() + <span class="hljs-string">""</span>); mTv.setText(us.get(<span class="hljs-number">1</span>).toString()); } });</code>
唯一的区别,就是泛型变为List<User>
,ok , 如果发现bug或者有任何意见欢迎留言。
ok,基本介绍完了,对于封装的代码其实也很简单,我就直接贴出来了,因为也没什么好介绍的,如果你看完上面的用法,肯定可以看懂:
<code class="language-java hljs has-numbering"><span class="hljs-keyword">package</span> com.zhy.utils.http.okhttp; <span class="hljs-keyword">import</span> android.graphics.Bitmap; <span class="hljs-keyword">import</span> android.graphics.BitmapFactory; <span class="hljs-keyword">import</span> android.os.Handler; <span class="hljs-keyword">import</span> android.os.Looper; <span class="hljs-keyword">import</span> android.widget.ImageView; <span class="hljs-keyword">import</span> com.google.gson.Gson; <span class="hljs-keyword">import</span> com.google.gson.internal.$Gson$Types; <span class="hljs-keyword">import</span> com.squareup.okhttp.Call; <span class="hljs-keyword">import</span> com.squareup.okhttp.Callback; <span class="hljs-keyword">import</span> com.squareup.okhttp.FormEncodingBuilder; <span class="hljs-keyword">import</span> com.squareup.okhttp.Headers; <span class="hljs-keyword">import</span> com.squareup.okhttp.MediaType; <span class="hljs-keyword">import</span> com.squareup.okhttp.MultipartBuilder; <span class="hljs-keyword">import</span> com.squareup.okhttp.OkHttpClient; <span class="hljs-keyword">import</span> com.squareup.okhttp.Request; <span class="hljs-keyword">import</span> com.squareup.okhttp.RequestBody; <span class="hljs-keyword">import</span> com.squareup.okhttp.Response; <span class="hljs-keyword">import</span> java.io.File; <span class="hljs-keyword">import</span> java.io.FileOutputStream; <span class="hljs-keyword">import</span> java.io.IOException; <span class="hljs-keyword">import</span> java.io.InputStream; <span class="hljs-keyword">import</span> java.lang.reflect.ParameterizedType; <span class="hljs-keyword">import</span> java.lang.reflect.Type; <span class="hljs-keyword">import</span> java.net.CookieManager; <span class="hljs-keyword">import</span> java.net.CookiePolicy; <span class="hljs-keyword">import</span> java.net.FileNameMap; <span class="hljs-keyword">import</span> java.net.URLConnection; <span class="hljs-keyword">import</span> java.util.HashMap; <span class="hljs-keyword">import</span> java.util.Map; <span class="hljs-keyword">import</span> java.util.Set; <span class="hljs-javadoc">/** * Created by zhy on 15/8/17. */</span> <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OkHttpClientManager</span> {</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> OkHttpClientManager mInstance; <span class="hljs-keyword">private</span> OkHttpClient mOkHttpClient; <span class="hljs-keyword">private</span> Handler mDelivery; <span class="hljs-keyword">private</span> Gson mGson; <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> String TAG = <span class="hljs-string">"OkHttpClientManager"</span>; <span class="hljs-keyword">private</span> <span class="hljs-title">OkHttpClientManager</span>() { mOkHttpClient = <span class="hljs-keyword">new</span> OkHttpClient(); <span class="hljs-comment">//cookie enabled</span> mOkHttpClient.setCookieHandler(<span class="hljs-keyword">new</span> CookieManager(<span class="hljs-keyword">null</span>, CookiePolicy.ACCEPT_ORIGINAL_SERVER)); mDelivery = <span class="hljs-keyword">new</span> Handler(Looper.getMainLooper()); mGson = <span class="hljs-keyword">new</span> Gson(); } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> OkHttpClientManager <span class="hljs-title">getInstance</span>() { <span class="hljs-keyword">if</span> (mInstance == <span class="hljs-keyword">null</span>) { <span class="hljs-keyword">synchronized</span> (OkHttpClientManager.class) { <span class="hljs-keyword">if</span> (mInstance == <span class="hljs-keyword">null</span>) { mInstance = <span class="hljs-keyword">new</span> OkHttpClientManager(); } } } <span class="hljs-keyword">return</span> mInstance; } <span class="hljs-javadoc">/** * 同步的Get请求 * *<span class="hljs-javadoctag"> @param</span> url *<span class="hljs-javadoctag"> @return</span> Response */</span> <span class="hljs-keyword">private</span> Response <span class="hljs-title">_getAsyn</span>(String url) <span class="hljs-keyword">throws</span> IOException { <span class="hljs-keyword">final</span> Request request = <span class="hljs-keyword">new</span> Request.Builder() .url(url) .build(); Call call = mOkHttpClient.newCall(request); Response execute = call.execute(); <span class="hljs-keyword">return</span> execute; } <span class="hljs-javadoc">/** * 同步的Get请求 * *<span class="hljs-javadoctag"> @param</span> url *<span class="hljs-javadoctag"> @return</span> 字符串 */</span> <span class="hljs-keyword">private</span> String <span class="hljs-title">_getAsString</span>(String url) <span class="hljs-keyword">throws</span> IOException { Response execute = _getAsyn(url); <span class="hljs-keyword">return</span> execute.body().string(); } <span class="hljs-javadoc">/** * 异步的get请求 * *<span class="hljs-javadoctag"> @param</span> url *<span class="hljs-javadoctag"> @param</span> callback */</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">_getAsyn</span>(String url, <span class="hljs-keyword">final</span> ResultCallback callback) { <span class="hljs-keyword">final</span> Request request = <span class="hljs-keyword">new</span> Request.Builder() .url(url) .build(); deliveryResult(callback, request); } <span class="hljs-javadoc">/** * 同步的Post请求 * *<span class="hljs-javadoctag"> @param</span> url *<span class="hljs-javadoctag"> @param</span> params post的参数 *<span class="hljs-javadoctag"> @return</span> */</span> <span class="hljs-keyword">private</span> Response <span class="hljs-title">_post</span>(String url, Param... params) <span class="hljs-keyword">throws</span> IOException { Request request = buildPostRequest(url, params); Response response = mOkHttpClient.newCall(request).execute(); <span class="hljs-keyword">return</span> response; } <span class="hljs-javadoc">/** * 同步的Post请求 * *<span class="hljs-javadoctag"> @param</span> url *<span class="hljs-javadoctag"> @param</span> params post的参数 *<span class="hljs-javadoctag"> @return</span> 字符串 */</span> <span class="hljs-keyword">private</span> String <span class="hljs-title">_postAsString</span>(String url, Param... params) <span class="hljs-keyword">throws</span> IOException { Response response = _post(url, params); <span class="hljs-keyword">return</span> response.body().string(); } <span class="hljs-javadoc">/** * 异步的post请求 * *<span class="hljs-javadoctag"> @param</span> url *<span class="hljs-javadoctag"> @param</span> callback *<span class="hljs-javadoctag"> @param</span> params */</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">_postAsyn</span>(String url, <span class="hljs-keyword">final</span> ResultCallback callback, Param... params) { Request request = buildPostRequest(url, params); deliveryResult(callback, request); } <span class="hljs-javadoc">/** * 异步的post请求 * *<span class="hljs-javadoctag"> @param</span> url *<span class="hljs-javadoctag"> @param</span> callback *<span class="hljs-javadoctag"> @param</span> params */</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">_postAsyn</span>(String url, <span class="hljs-keyword">final</span> ResultCallback callback, Map<String, String> params) { Param[] paramsArr = map2Params(params); Request request = buildPostRequest(url, paramsArr); deliveryResult(callback, request); } <span class="hljs-javadoc">/** * 同步基于post的文件上传 * *<span class="hljs-javadoctag"> @param</span> params *<span class="hljs-javadoctag"> @return</span> */</span> <span class="hljs-keyword">private</span> Response <span class="hljs-title">_post</span>(String url, File[] files, String[] fileKeys, Param... params) <span class="hljs-keyword">throws</span> IOException { Request request = buildMultipartFormRequest(url, files, fileKeys, params); <span class="hljs-keyword">return</span> mOkHttpClient.newCall(request).execute(); } <span class="hljs-keyword">private</span> Response <span class="hljs-title">_post</span>(String url, File file, String fileKey) <span class="hljs-keyword">throws</span> IOException { Request request = buildMultipartFormRequest(url, <span class="hljs-keyword">new</span> File[]{file}, <span class="hljs-keyword">new</span> String[]{fileKey}, <span class="hljs-keyword">null</span>); <span class="hljs-keyword">return</span> mOkHttpClient.newCall(request).execute(); } <span class="hljs-keyword">private</span> Response <span class="hljs-title">_post</span>(String url, File file, String fileKey, Param... params) <span class="hljs-keyword">throws</span> IOException { Request request = buildMultipartFormRequest(url, <span class="hljs-keyword">new</span> File[]{file}, <span class="hljs-keyword">new</span> String[]{fileKey}, params); <span class="hljs-keyword">return</span> mOkHttpClient.newCall(request).execute(); } <span class="hljs-javadoc">/** * 异步基于post的文件上传 * *<span class="hljs-javadoctag"> @param</span> url *<span class="hljs-javadoctag"> @param</span> callback *<span class="hljs-javadoctag"> @param</span> files *<span class="hljs-javadoctag"> @param</span> fileKeys *<span class="hljs-javadoctag"> @throws</span> IOException */</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">_postAsyn</span>(String url, ResultCallback callback, File[] files, String[] fileKeys, Param... params) <span class="hljs-keyword">throws</span> IOException { Request request = buildMultipartFormRequest(url, files, fileKeys, params); deliveryResult(callback, request); } <span class="hljs-javadoc">/** * 异步基于post的文件上传,单文件不带参数上传 * *<span class="hljs-javadoctag"> @param</span> url *<span class="hljs-javadoctag"> @param</span> callback *<span class="hljs-javadoctag"> @param</span> file *<span class="hljs-javadoctag"> @param</span> fileKey *<span class="hljs-javadoctag"> @throws</span> IOException */</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">_postAsyn</span>(String url, ResultCallback callback, File file, String fileKey) <span class="hljs-keyword">throws</span> IOException { Request request = buildMultipartFormRequest(url, <span class="hljs-keyword">new</span> File[]{file}, <span class="hljs-keyword">new</span> String[]{fileKey}, <span class="hljs-keyword">null</span>); deliveryResult(callback, request); } <span class="hljs-javadoc">/** * 异步基于post的文件上传,单文件且携带其他form参数上传 * *<span class="hljs-javadoctag"> @param</span> url *<span class="hljs-javadoctag"> @param</span> callback *<span class="hljs-javadoctag"> @param</span> file *<span class="hljs-javadoctag"> @param</span> fileKey *<span class="hljs-javadoctag"> @param</span> params *<span class="hljs-javadoctag"> @throws</span> IOException */</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">_postAsyn</span>(String url, ResultCallback callback, File file, String fileKey, Param... params) <span class="hljs-keyword">throws</span> IOException { Request request = buildMultipartFormRequest(url, <span class="hljs-keyword">new</span> File[]{file}, <span class="hljs-keyword">new</span> String[]{fileKey}, params); deliveryResult(callback, request); } <span class="hljs-javadoc">/** * 异步下载文件 * *<span class="hljs-javadoctag"> @param</span> url *<span class="hljs-javadoctag"> @param</span> destFileDir 本地文件存储的文件夹 *<span class="hljs-javadoctag"> @param</span> callback */</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">_downloadAsyn</span>(<span class="hljs-keyword">final</span> String url, <span class="hljs-keyword">final</span> String destFileDir, <span class="hljs-keyword">final</span> ResultCallback callback) { <span class="hljs-keyword">final</span> Request request = <span class="hljs-keyword">new</span> Request.Builder() .url(url) .build(); <span class="hljs-keyword">final</span> Call call = mOkHttpClient.newCall(request); call.enqueue(<span class="hljs-keyword">new</span> Callback() { <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onFailure</span>(<span class="hljs-keyword">final</span> Request request, <span class="hljs-keyword">final</span> IOException e) { sendFailedStringCallback(request, e, callback); } <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onResponse</span>(Response response) { InputStream is = <span class="hljs-keyword">null</span>; <span class="hljs-keyword">byte</span>[] buf = <span class="hljs-keyword">new</span> <span class="hljs-keyword">byte</span>[<span class="hljs-number">2048</span>]; <span class="hljs-keyword">int</span> len = <span class="hljs-number">0</span>; FileOutputStream fos = <span class="hljs-keyword">null</span>; <span class="hljs-keyword">try</span> { is = response.body().byteStream(); File file = <span class="hljs-keyword">new</span> File(destFileDir, getFileName(url)); fos = <span class="hljs-keyword">new</span> FileOutputStream(file); <span class="hljs-keyword">while</span> ((len = is.read(buf)) != -<span class="hljs-number">1</span>) { fos.write(buf, <span class="hljs-number">0</span>, len); } fos.flush(); <span class="hljs-comment">//如果下载文件成功,第一个参数为文件的绝对路径</span> sendSuccessResultCallback(file.getAbsolutePath(), callback); } <span class="hljs-keyword">catch</span> (IOException e) { sendFailedStringCallback(response.request(), e, callback); } <span class="hljs-keyword">finally</span> { <span class="hljs-keyword">try</span> { <span class="hljs-keyword">if</span> (is != <span class="hljs-keyword">null</span>) is.close(); } <span class="hljs-keyword">catch</span> (IOException e) { } <span class="hljs-keyword">try</span> { <span class="hljs-keyword">if</span> (fos != <span class="hljs-keyword">null</span>) fos.close(); } <span class="hljs-keyword">catch</span> (IOException e) { } } } }); } <span class="hljs-keyword">private</span> String <span class="hljs-title">getFileName</span>(String path) { <span class="hljs-keyword">int</span> separatorIndex = path.lastIndexOf(<span class="hljs-string">"/"</span>); <span class="hljs-keyword">return</span> (separatorIndex < <span class="hljs-number">0</span>) ? path : path.substring(separatorIndex + <span class="hljs-number">1</span>, path.length()); } <span class="hljs-javadoc">/** * 加载图片 * *<span class="hljs-javadoctag"> @param</span> view *<span class="hljs-javadoctag"> @param</span> url *<span class="hljs-javadoctag"> @throws</span> IOException */</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">_displayImage</span>(<span class="hljs-keyword">final</span> ImageView view, <span class="hljs-keyword">final</span> String url, <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> errorResId) { <span class="hljs-keyword">final</span> Request request = <span class="hljs-keyword">new</span> Request.Builder() .url(url) .build(); Call call = mOkHttpClient.newCall(request); call.enqueue(<span class="hljs-keyword">new</span> Callback() { <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onFailure</span>(Request request, IOException e) { setErrorResId(view, errorResId); } <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onResponse</span>(Response response) { InputStream is = <span class="hljs-keyword">null</span>; <span class="hljs-keyword">try</span> { is = response.body().byteStream(); ImageUtils.ImageSize actualImageSize = ImageUtils.getImageSize(is); ImageUtils.ImageSize imageViewSize = ImageUtils.getImageViewSize(view); <span class="hljs-keyword">int</span> inSampleSize = ImageUtils.calculateInSampleSize(actualImageSize, imageViewSize); <span class="hljs-keyword">try</span> { is.reset(); } <span class="hljs-keyword">catch</span> (IOException e) { response = _getAsyn(url); is = response.body().byteStream(); } BitmapFactory.Options ops = <span class="hljs-keyword">new</span> BitmapFactory.Options(); ops.inJustDecodeBounds = <span class="hljs-keyword">false</span>; ops.inSampleSize = inSampleSize; <span class="hljs-keyword">final</span> Bitmap bm = BitmapFactory.decodeStream(is, <span class="hljs-keyword">null</span>, ops); mDelivery.post(<span class="hljs-keyword">new</span> Runnable() { <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span>() { view.setImageBitmap(bm); } }); } <span class="hljs-keyword">catch</span> (Exception e) { setErrorResId(view, errorResId); } <span class="hljs-keyword">finally</span> { <span class="hljs-keyword">if</span> (is != <span class="hljs-keyword">null</span>) <span class="hljs-keyword">try</span> { is.close(); } <span class="hljs-keyword">catch</span> (IOException e) { e.printStackTrace(); } } } }); } <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setErrorResId</span>(<span class="hljs-keyword">final</span> ImageView view, <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> errorResId) { mDelivery.post(<span class="hljs-keyword">new</span> Runnable() { <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span>() { view.setImageResource(errorResId); } }); } <span class="hljs-comment">//*************对外公布的方法************</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Response <span class="hljs-title">getAsyn</span>(String url) <span class="hljs-keyword">throws</span> IOException { <span class="hljs-keyword">return</span> getInstance()._getAsyn(url); } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> String <span class="hljs-title">getAsString</span>(String url) <span class="hljs-keyword">throws</span> IOException { <span class="hljs-keyword">return</span> getInstance()._getAsString(url); } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getAsyn</span>(String url, ResultCallback callback) { getInstance()._getAsyn(url, callback); } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Response <span class="hljs-title">post</span>(String url, Param... params) <span class="hljs-keyword">throws</span> IOException { <span class="hljs-keyword">return</span> getInstance()._post(url, params); } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> String <span class="hljs-title">postAsString</span>(String url, Param... params) <span class="hljs-keyword">throws</span> IOException { <span class="hljs-keyword">return</span> getInstance()._postAsString(url, params); } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">postAsyn</span>(String url, <span class="hljs-keyword">final</span> ResultCallback callback, Param... params) { getInstance()._postAsyn(url, callback, params); } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">postAsyn</span>(String url, <span class="hljs-keyword">final</span> ResultCallback callback, Map<String, String> params) { getInstance()._postAsyn(url, callback, params); } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Response <span class="hljs-title">post</span>(String url, File[] files, String[] fileKeys, Param... params) <span class="hljs-keyword">throws</span> IOException { <span class="hljs-keyword">return</span> getInstance()._post(url, files, fileKeys, params); } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Response <span class="hljs-title">post</span>(String url, File file, String fileKey) <span class="hljs-keyword">throws</span> IOException { <span class="hljs-keyword">return</span> getInstance()._post(url, file, fileKey); } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Response <span class="hljs-title">post</span>(String url, File file, String fileKey, Param... params) <span class="hljs-keyword">throws</span> IOException { <span class="hljs-keyword">return</span> getInstance()._post(url, file, fileKey, params); } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">postAsyn</span>(String url, ResultCallback callback, File[] files, String[] fileKeys, Param... params) <span class="hljs-keyword">throws</span> IOException { getInstance()._postAsyn(url, callback, files, fileKeys, params); } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">postAsyn</span>(String url, ResultCallback callback, File file, String fileKey) <span class="hljs-keyword">throws</span> IOException { getInstance()._postAsyn(url, callback, file, fileKey); } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">postAsyn</span>(String url, ResultCallback callback, File file, String fileKey, Param... params) <span class="hljs-keyword">throws</span> IOException { getInstance()._postAsyn(url, callback, file, fileKey, params); } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">displayImage</span>(<span class="hljs-keyword">final</span> ImageView view, String url, <span class="hljs-keyword">int</span> errorResId) <span class="hljs-keyword">throws</span> IOException { getInstance()._displayImage(view, url, errorResId); } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">displayImage</span>(<span class="hljs-keyword">final</span> ImageView view, String url) { getInstance()._displayImage(view, url, -<span class="hljs-number">1</span>); } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">downloadAsyn</span>(String url, String destDir, ResultCallback callback) { getInstance()._downloadAsyn(url, destDir, callback); } <span class="hljs-comment">//****************************</span> <span class="hljs-keyword">private</span> Request <span class="hljs-title">buildMultipartFormRequest</span>(String url, File[] files, String[] fileKeys, Param[] params) { params = validateParam(params); MultipartBuilder builder = <span class="hljs-keyword">new</span> MultipartBuilder() .type(MultipartBuilder.FORM); <span class="hljs-keyword">for</span> (Param param : params) { builder.addPart(Headers.of(<span class="hljs-string">"Content-Disposition"</span>, <span class="hljs-string">"form-data; name=\""</span> + param.key + <span class="hljs-string">"\""</span>), RequestBody.create(<span class="hljs-keyword">null</span>, param.value)); } <span class="hljs-keyword">if</span> (files != <span class="hljs-keyword">null</span>) { RequestBody fileBody = <span class="hljs-keyword">null</span>; <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i < files.length; i++) { File file = files[i]; String fileName = file.getName(); fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file); <span class="hljs-comment">//TODO 根据文件名设置contentType</span> builder.addPart(Headers.of(<span class="hljs-string">"Content-Disposition"</span>, <span class="hljs-string">"form-data; name=\""</span> + fileKeys[i] + <span class="hljs-string">"\"; filename=\""</span> + fileName + <span class="hljs-string">"\""</span>), fileBody); } } RequestBody requestBody = builder.build(); <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Request.Builder() .url(url) .post(requestBody) .build(); } <span class="hljs-keyword">private</span> String <span class="hljs-title">guessMimeType</span>(String path) { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String contentTypeFor = fileNameMap.getContentTypeFor(path); <span class="hljs-keyword">if</span> (contentTypeFor == <span class="hljs-keyword">null</span>) { contentTypeFor = <span class="hljs-string">"application/octet-stream"</span>; } <span class="hljs-keyword">return</span> contentTypeFor; } <span class="hljs-keyword">private</span> Param[] <span class="hljs-title">validateParam</span>(Param[] params) { <span class="hljs-keyword">if</span> (params == <span class="hljs-keyword">null</span>) <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Param[<span class="hljs-number">0</span>]; <span class="hljs-keyword">else</span> <span class="hljs-keyword">return</span> params; } <span class="hljs-keyword">private</span> Param[] <span class="hljs-title">map2Params</span>(Map<String, String> params) { <span class="hljs-keyword">if</span> (params == <span class="hljs-keyword">null</span>) <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Param[<span class="hljs-number">0</span>]; <span class="hljs-keyword">int</span> size = params.size(); Param[] res = <span class="hljs-keyword">new</span> Param[size]; Set<Map.Entry<String, String>> entries = params.entrySet(); <span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; <span class="hljs-keyword">for</span> (Map.Entry<String, String> entry : entries) { res[i++] = <span class="hljs-keyword">new</span> Param(entry.getKey(), entry.getValue()); } <span class="hljs-keyword">return</span> res; } <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> String SESSION_KEY = <span class="hljs-string">"Set-Cookie"</span>; <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> String mSessionKey = <span class="hljs-string">"JSESSIONID"</span>; <span class="hljs-keyword">private</span> Map<String, String> mSessions = <span class="hljs-keyword">new</span> HashMap<String, String>(); <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deliveryResult</span>(<span class="hljs-keyword">final</span> ResultCallback callback, Request request) { mOkHttpClient.newCall(request).enqueue(<span class="hljs-keyword">new</span> Callback() { <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onFailure</span>(<span class="hljs-keyword">final</span> Request request, <span class="hljs-keyword">final</span> IOException e) { sendFailedStringCallback(request, e, callback); } <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onResponse</span>(<span class="hljs-keyword">final</span> Response response) { <span class="hljs-keyword">try</span> { <span class="hljs-keyword">final</span> String string = response.body().string(); <span class="hljs-keyword">if</span> (callback.mType == String.class) { sendSuccessResultCallback(string, callback); } <span class="hljs-keyword">else</span> { Object o = mGson.fromJson(string, callback.mType); sendSuccessResultCallback(o, callback); } } <span class="hljs-keyword">catch</span> (IOException e) { sendFailedStringCallback(response.request(), e, callback); } <span class="hljs-keyword">catch</span> (com.google.gson.JsonParseException e)<span class="hljs-comment">//Json解析的错误</span> { sendFailedStringCallback(response.request(), e, callback); } } }); } <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">sendFailedStringCallback</span>(<span class="hljs-keyword">final</span> Request request, <span class="hljs-keyword">final</span> Exception e, <span class="hljs-keyword">final</span> ResultCallback callback) { mDelivery.post(<span class="hljs-keyword">new</span> Runnable() { <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span>() { <span class="hljs-keyword">if</span> (callback != <span class="hljs-keyword">null</span>) callback.onError(request, e); } }); } <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">sendSuccessResultCallback</span>(<span class="hljs-keyword">final</span> Object object, <span class="hljs-keyword">final</span> ResultCallback callback) { mDelivery.post(<span class="hljs-keyword">new</span> Runnable() { <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span>() { <span class="hljs-keyword">if</span> (callback != <span class="hljs-keyword">null</span>) { callback.onResponse(object); } } }); } <span class="hljs-keyword">private</span> Request <span class="hljs-title">buildPostRequest</span>(String url, Param[] params) { <span class="hljs-keyword">if</span> (params == <span class="hljs-keyword">null</span>) { params = <span class="hljs-keyword">new</span> Param[<span class="hljs-number">0</span>]; } FormEncodingBuilder builder = <span class="hljs-keyword">new</span> FormEncodingBuilder(); <span class="hljs-keyword">for</span> (Param param : params) { builder.add(param.key, param.value); } RequestBody requestBody = builder.build(); <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Request.Builder() .url(url) .post(requestBody) .build(); } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ResultCallback</span><<span class="hljs-title">T</span>> {</span> Type mType; <span class="hljs-keyword">public</span> <span class="hljs-title">ResultCallback</span>() { mType = getSuperclassTypeParameter(getClass()); } <span class="hljs-keyword">static</span> Type getSuperclassTypeParameter(Class<?> subclass) { Type superclass = subclass.getGenericSuperclass(); <span class="hljs-keyword">if</span> (superclass <span class="hljs-keyword">instanceof</span> Class) { <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(<span class="hljs-string">"Missing type parameter."</span>); } ParameterizedType parameterized = (ParameterizedType) superclass; <span class="hljs-keyword">return</span> $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[<span class="hljs-number">0</span>]); } <span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onError</span>(Request request, Exception e); <span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onResponse</span>(T response); } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Param</span> {</span> <span class="hljs-keyword">public</span> <span class="hljs-title">Param</span>() { } <span class="hljs-keyword">public</span> <span class="hljs-title">Param</span>(String key, String value) { <span class="hljs-keyword">this</span>.key = key; <span class="hljs-keyword">this</span>.value = value; } String key; String value; } }</code>
源码地址okhttp-utils,大家可以自己下载查看。
转自:http://blog.csdn.net/lmj623565791/article/details/47911083