本文主要是介绍Android 使用OkHttp,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
为什么需要一个HTTP库
Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient。
关于HttpURLConnection和HttpClient的选择>>官方博客
尽管Google在大部分安卓版本中推荐使用HttpURLConnection,但是这个类相比HttpClient实在是太难用,太弱爆了。
OkHttp是一个相对成熟的解决方案,据说Android4.4的源码中可以看到HttpURLConnection已经替换成OkHttp实现了。所以我们更有理由相信OkHttp的强大。
入门
官方资料
官方介绍
github源码使用范围
OkHttp支持Android 2.3及其以上版本。 对于Java, JDK1.7以上。
jar包准备
官方介绍页面有链接位置。这里把下载链接也写在下面。
OkHttp
Okio基本使用
HTTP GET
<code style="padding: 0.3em; font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; border: 0px; display: block; overflow-y: auto;">OkHttpClient client = <span class="keyword" style="font-weight: bold;">new</span> OkHttpClient();String run(String url) throws IOException { <span class="indent"> </span>Request request = <span class="keyword" style="font-weight: bold;">new</span> Request.Builder().url(url).build(); <span class="indent"> </span>Response response = client.newCall(request).execute(); <span class="indent"> </span><span class="keyword" style="font-weight: bold;">if</span> (response.isSuccessful()) { <span class="indent"> </span><span class="indent"> </span><span class="keyword" style="font-weight: bold;">return</span> response.body().<span class="keyword" style="font-weight: bold;">string</span>(); <span class="indent"> </span>} <span class="keyword" style="font-weight: bold;">else</span> { <span class="indent"> </span><span class="indent"> </span><span class="keyword" style="font-weight: bold;">throw</span> <span class="keyword" style="font-weight: bold;">new</span> IOException(<span class="string" style="color: rgb(221, 17, 68);">"Unexpected code "</span> + response); <span class="indent"> </span>} }</code>
Request是OkHttp中访问的请求,Builder是辅助类。Response即OkHttp中的响应。
Response类:
<code style="padding: 0.3em; font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; border: 0px; display: block; overflow-y: auto;"><span class="keyword" style="font-weight: bold;">public</span> boolean isSuccessful() Returns <span class="keyword" style="font-weight: bold;">true</span> <span class="keyword" style="font-weight: bold;">if</span> the code <span class="keyword" style="font-weight: bold;">is</span> <span class="keyword" style="font-weight: bold;">in</span> [<span class="number" style="color: rgb(0, 153, 153);">200.</span><span class="number" style="color: rgb(0, 153, 153);">.300</span>), which means the request was successfully received, understood, and accepted.</code>
response.body()返回ResponseBody类
可以方便的获取string
<code style="padding: 0.3em; font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; border: 0px; display: block; overflow-y: auto;"><span class="keyword" style="font-weight: bold;">public</span> final String <span class="keyword" style="font-weight: bold;">string</span>() throws IOException Returns the response <span class="keyword" style="font-weight: bold;">as</span> a <span class="keyword" style="font-weight: bold;">string</span> decoded with the charset of the Content-Type header. If that header <span class="keyword" style="font-weight: bold;">is</span> either absent or lacks a charset, <span class="keyword" style="font-weight: bold;">this</span> will attempt to decode the response body <span class="keyword" style="font-weight: bold;">as</span> UTF-<span class="number" style="color: rgb(0, 153, 153);">8.</span> Throws: IOException</code>
当然也能获取到流的形式:
<code style="padding: 0.3em; font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; border: 0px; display: block; overflow-y: auto;"><span class="keyword" style="font-weight: bold;">public</span> <span class="keyword" style="font-weight: bold;">final</span> InputStream byteStream()</code>
HTTP POST
POST提交Json数据
<code style="padding: 0.3em; font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; border: 0px; display: block; overflow-y: auto;"><span class="keyword" style="font-weight: bold;">public</span> <span class="keyword" style="font-weight: bold;">static</span> <span class="keyword" style="font-weight: bold;">final</span> MediaType JSON = MediaType.parse(<span class="string" style="color: rgb(221, 17, 68);">"application/json; charset=utf-8"</span>);
OkHttpClient client = <span class="keyword" style="font-weight: bold;">new</span> OkHttpClient();
String post(String url, String json) <span class="keyword" style="font-weight: bold;">throws</span> IOException {RequestBody body = RequestBody.create(JSON, json);Request request = <span class="keyword" style="font-weight: bold;">new</span> Request.Builder()
<span class="indent"> </span> .url(url)
<span class="indent"> </span> .post(body)
<span class="indent"> </span> .build();Response response = client.newCall(request).execute();
<span class="indent"> </span>f (response.isSuccessful()) {
<span class="indent"> </span><span class="indent"> </span><span class="keyword" style="font-weight: bold;">return</span> response.body().string();
<span class="indent"> </span>} <span class="keyword" style="font-weight: bold;">else</span> {
<span class="indent"> </span><span class="indent"> </span><span class="keyword" style="font-weight: bold;">throw</span> <span class="keyword" style="font-weight: bold;">new</span> IOException(<span class="string" style="color: rgb(221, 17, 68);">"Unexpected code "</span> + response);
<span class="indent"> </span>}
}</code>
使用Request的post方法来提交请求体RequestBody
POST提交键值对
很多时候我们会需要通过POST方式把键值对数据传送到服务器。 OkHttp提供了很方便的方式来做这件事情。
<code style="padding: 0.3em; font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; border: 0px; display: block; overflow-y: auto;">OkHttpClient client = <span class="keyword" style="font-weight: bold;">new</span> OkHttpClient(); String post(String url, String json) throws IOException {RequestBody formBody = <span class="keyword" style="font-weight: bold;">new</span> FormEncodingBuilder() <span class="indent"> </span>.add(<span class="string" style="color: rgb(221, 17, 68);">"platform"</span>, <span class="string" style="color: rgb(221, 17, 68);">"android"</span>) <span class="indent"> </span>.add(<span class="string" style="color: rgb(221, 17, 68);">"name"</span>, <span class="string" style="color: rgb(221, 17, 68);">"bug"</span>) <span class="indent"> </span>.add(<span class="string" style="color: rgb(221, 17, 68);">"subject"</span>, <span class="string" style="color: rgb(221, 17, 68);">"XXXXXXXXXXXXXXX"</span>) <span class="indent"> </span>.build();Request request = <span class="keyword" style="font-weight: bold;">new</span> Request.Builder().url(url).post(body).build();Response response = client.newCall(request).execute(); <span class="indent"> </span><span class="keyword" style="font-weight: bold;">if</span> (response.isSuccessful()) { <span class="indent"> </span> <span class="keyword" style="font-weight: bold;">return</span> response.body().<span class="keyword" style="font-weight: bold;">string</span>(); <span class="indent"> </span>} <span class="keyword" style="font-weight: bold;">else</span> { <span class="indent"> </span> <span class="keyword" style="font-weight: bold;">throw</span> <span class="keyword" style="font-weight: bold;">new</span> IOException(<span class="string" style="color: rgb(221, 17, 68);">"Unexpected code "</span> + response); <span class="indent"> </span>} }</code>
总结
通过上面的例子我们可以发现,OkHttp在很多时候使用都是很方便的,而且很多代码也有重复,因此特地整理了下面的工具类。 注意:
- OkHttp官方文档并不建议我们创建多个OkHttpClient,因此全局使用一个。 如果有需要,可以使用clone方法,再进行自定义。这点在后面的高级教程里会提到。
- enqueue为OkHttp提供的异步方法,入门教程中并没有提到,后面的高级教程里会有解释。
<code style="padding: 0.3em; font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; border: 0px; display: block; overflow-y: auto;"><span class="keyword" style="font-weight: bold;">import</span> java.io.IOException;
<span class="keyword" style="font-weight: bold;">import</span> java.util.List;
<span class="keyword" style="font-weight: bold;">import</span> java.util.concurrent.TimeUnit;
<span class="keyword" style="font-weight: bold;">import</span> org.apache.http.client.utils.URLEncodedUtils;
<span class="keyword" style="font-weight: bold;">import</span> org.apache.http.message.BasicNameValuePair;
<span class="keyword" style="font-weight: bold;">import</span> cn.wiz.sdk.constant.WizConstant;
<span class="keyword" style="font-weight: bold;">import</span> com.squareup.okhttp.Callback;
<span class="keyword" style="font-weight: bold;">import</span> com.squareup.okhttp.OkHttpClient;
<span class="keyword" style="font-weight: bold;">import</span> com.squareup.okhttp.Request;
<span class="keyword" style="font-weight: bold;">import</span> com.squareup.okhttp.Response; <span class="keyword" style="font-weight: bold;">public</span> <span class="class" style="color: rgb(68, 85, 136); font-weight: bold;"><span class="keyword" style="color: rgb(51, 51, 51);">class</span> <span class="title">OkHttpUtil</span> {</span>
<span class="indent"> </span><span class="keyword" style="font-weight: bold;">private</span> <span class="keyword" style="font-weight: bold;">static</span> <span class="keyword" style="font-weight: bold;">final</span> OkHttpClient mOkHttpClient = <span class="keyword" style="font-weight: bold;">new</span> OkHttpClient();
<span class="indent"> </span><span class="keyword" style="font-weight: bold;">static</span>{
<span class="indent"> </span><span class="indent"> </span>mOkHttpClient.setConnectTimeout(<span class="number" style="color: rgb(0, 153, 153);">30</span>, TimeUnit.SECONDS);
<span class="indent"> </span>}
<span class="indent"> </span><span class="javadoc" style="color: rgb(153, 153, 136); font-style: italic;">/**
<span class="indent"> </span> * 该不会开启异步线程。
<span class="indent"> </span> * <span class="javadoctag">@param</span> request
<span class="indent"> </span> * <span class="javadoctag">@return</span>
<span class="indent"> </span> * <span class="javadoctag">@throws</span> IOException
<span class="indent"> </span> */</span>
<span class="indent"> </span><span class="keyword" style="font-weight: bold;">public</span> <span class="keyword" style="font-weight: bold;">static</span> Response execute(Request request) <span class="keyword" style="font-weight: bold;">throws</span> IOException{
<span class="indent"> </span><span class="indent"> </span><span class="keyword" style="font-weight: bold;">return</span> mOkHttpClient.newCall(request).execute();
<span class="indent"> </span>}
<span class="indent"> </span><span class="javadoc" style="color: rgb(153, 153, 136); font-style: italic;">/**
<span class="indent"> </span> * 开启异步线程访问网络
<span class="indent"> </span> * <span class="javadoctag">@param</span> request
<span class="indent"> </span> * <span class="javadoctag">@param</span> responseCallback
<span class="indent"> </span> */</span>
<span class="indent"> </span><span class="keyword" style="font-weight: bold;">public</span> <span class="keyword" style="font-weight: bold;">static</span> <span class="keyword" style="font-weight: bold;">void</span> enqueue(Request request, Callback responseCallback){
<span class="indent"> </span><span class="indent"> </span>mOkHttpClient.newCall(request).enqueue(responseCallback);
<span class="indent"> </span>}
<span class="indent"> </span><span class="javadoc" style="color: rgb(153, 153, 136); font-style: italic;">/**
<span class="indent"> </span> * 开启异步线程访问网络, 且不在意返回结果(实现空callback)
<span class="indent"> </span> * <span class="javadoctag">@param</span> request
<span class="indent"> </span> */</span>
<span class="indent"> </span><span class="keyword" style="font-weight: bold;">public</span> <span class="keyword" style="font-weight: bold;">static</span> <span class="keyword" style="font-weight: bold;">void</span> enqueue(Request request){
<span class="indent"> </span><span class="indent"> </span>mOkHttpClient.newCall(request).enqueue(<span class="keyword" style="font-weight: bold;">new</span> Callback() {
<span class="indent"> </span><span class="indent"> </span><span class="indent"> </span>
<span class="indent"> </span><span class="indent"> </span><span class="indent"> </span><span class="annotation">@Override</span>
<span class="indent"> </span><span class="indent"> </span><span class="indent"> </span><span class="keyword" style="font-weight: bold;">public</span> <span class="keyword" style="font-weight: bold;">void</span> onResponse(Response arg0) <span class="keyword" style="font-weight: bold;">throws</span> IOException {
<span class="indent"> </span><span class="indent"> </span><span class="indent"> </span><span class="indent"> </span>
<span class="indent"> </span><span class="indent"> </span><span class="indent"> </span>}
<span class="indent"> </span><span class="indent"> </span><span class="indent"> </span>
<span class="indent"> </span><span class="indent"> </span><span class="indent"> </span><span class="annotation">@Override</span>
<span class="indent"> </span><span class="indent"> </span><span class="indent"> </span><span class="keyword" style="font-weight: bold;">public</span> <span class="keyword" style="font-weight: bold;">void</span> onFailure(Request arg0, IOException arg1) {
<span class="indent"> </span><span class="indent"> </span><span class="indent"> </span><span class="indent"> </span>
<span class="indent"> </span><span class="indent"> </span><span class="indent"> </span>}
<span class="indent"> </span><span class="indent"> </span>});
<span class="indent"> </span>}
<span class="indent"> </span><span class="keyword" style="font-weight: bold;">public</span> <span class="keyword" style="font-weight: bold;">static</span> String getStringFromServer(String url) <span class="keyword" style="font-weight: bold;">throws</span> IOException{
<span class="indent"> </span><span class="indent"> </span>Request request = <span class="keyword" style="font-weight: bold;">new</span> Request.Builder().url(url).build();
<span class="indent"> </span><span class="indent"> </span>Response response = execute(request);
<span class="indent"> </span><span class="indent"> </span><span class="keyword" style="font-weight: bold;">if</span> (response.isSuccessful()) {
<span class="indent"> </span><span class="indent"> </span><span class="indent"> </span>String responseUrl = response.body().string();
<span class="indent"> </span><span class="indent"> </span><span class="indent"> </span><span class="keyword" style="font-weight: bold;">return</span> responseUrl;
<span class="indent"> </span><span class="indent"> </span>} <span class="keyword" style="font-weight: bold;">else</span> {
<span class="indent"> </span><span class="indent"> </span><span class="indent"> </span><span class="keyword" style="font-weight: bold;">throw</span> <span class="keyword" style="font-weight: bold;">new</span> IOException(<span class="string" style="color: rgb(221, 17, 68);">"Unexpected code "</span> + response);
<span class="indent"> </span><span class="indent"> </span>}
<span class="indent"> </span>}
<span class="indent"> </span><span class="keyword" style="font-weight: bold;">private</span> <span class="keyword" style="font-weight: bold;">static</span> <span class="keyword" style="font-weight: bold;">final</span> String CHARSET_NAME = <span class="string" style="color: rgb(221, 17, 68);">"UTF-8"</span>;
<span class="indent"> </span><span class="javadoc" style="color: rgb(153, 153, 136); font-style: italic;">/**
<span class="indent"> </span> * 这里使用了HttpClinet的API。只是为了方便
<span class="indent"> </span> * <span class="javadoctag">@param</span> params
<span class="indent"> </span> * <span class="javadoctag">@return</span>
<span class="indent"> </span> */</span>
<span class="indent"> </span><span class="keyword" style="font-weight: bold;">public</span> <span class="keyword" style="font-weight: bold;">static</span> String formatParams(List<BasicNameValuePair> params){
<span class="indent"> </span><span class="indent"> </span><span class="keyword" style="font-weight: bold;">return</span> URLEncodedUtils.format(params, CHARSET_NAME);
<span class="indent"> </span>}
<span class="indent"> </span><span class="javadoc" style="color: rgb(153, 153, 136); font-style: italic;">/**
<span class="indent"> </span> * 为HttpGet 的 url 方便的添加多个name value 参数。
<span class="indent"> </span> * <span class="javadoctag">@param</span> url
<span class="indent"> </span> * <span class="javadoctag">@param</span> params
<span class="indent"> </span> * <span class="javadoctag">@return</span>
<span class="indent"> </span> */</span>
<span class="indent"> </span><span class="keyword" style="font-weight: bold;">public</span> <span class="keyword" style="font-weight: bold;">static</span> String attachHttpGetParams(String url, List<BasicNameValuePair> params){
<span class="indent"> </span><span class="indent"> </span><span class="keyword" style="font-weight: bold;">return</span> url + <span class="string" style="color: rgb(221, 17, 68);">"?"</span> + formatParams(params);
<span class="indent"> </span>}
<span class="indent"> </span><span class="javadoc" style="color: rgb(153, 153, 136); font-style: italic;">/**
<span class="indent"> </span> * 为HttpGet 的 url 方便的添加1个name value 参数。
<span class="indent"> </span> * <span class="javadoctag">@param</span> url
<span class="indent"> </span> * <span class="javadoctag">@param</span> name
<span class="indent"> </span> * <span class="javadoctag">@param</span> value
<span class="indent"> </span> * <span class="javadoctag">@return</span>
<span class="indent"> </span> */</span>
<span class="indent"> </span><span class="keyword" style="font-weight: bold;">public</span> <span class="keyword" style="font-weight: bold;">static</span> String attachHttpGetParam(String url, String name, String value){
<span class="indent"> </span><span class="indent"> </span><span class="keyword" style="font-weight: bold;">return</span> url + <span class="string" style="color: rgb(221, 17, 68);">"?"</span> + name + <span class="string" style="color: rgb(221, 17, 68);">"="</span> + value;
<span class="indent"> </span>}
}</code>
高级
高级属性其实用的不多,这里主要是对OkHttp github官方教程进行了翻译。
请看我的另一篇博客: OkHttp使用进阶 译自OkHttp Github官方教程
这篇关于Android 使用OkHttp的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!