OkHttp使用介绍

版权声明:

欢迎转载,但请保留文章原始出处

作者:GavinCT

出处:http://www.cnblogs.com/ct2011/p/4001708.html

为什么需要一个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

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
    Request request = new Request.Builder().url(url).build();
    Response response = client.newCall(request).execute();
    if (response.isSuccessful()) {
        return response.body().string();
    } else {
        throw new IOException("Unexpected code " + response);
    }
}

Request是OkHttp中访问的请求,Builder是辅助类。Response即OkHttp中的响应。

Response类:

public boolean isSuccessful()
Returns true if the code is in [200..300), which means the request was successfully received, understood, and accepted.

response.body()返回ResponseBody类

可以方便的获取string

public final String string() throws IOException
Returns the response as a string decoded with the charset of the Content-Type header. If that header is either absent or lacks a charset, this will attempt to decode the response body as UTF-8.
Throws:
IOException

当然也能获取到流的形式:

public final InputStream byteStream()

HTTP POST

POST提交Json数据

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
 	RequestBody body = RequestBody.create(JSON, json);
  	Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  	Response response = client.newCall(request).execute();
	f (response.isSuccessful()) {
	    return response.body().string();
	} else {
	    throw new IOException("Unexpected code " + response);
	}
}

使用Request的post方法来提交请求体RequestBody

POST提交键值对

很多时候我们会需要通过POST方式把键值对数据传送到服务器。 OkHttp提供了很方便的方式来做这件事情。

OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {

 	RequestBody formBody = new FormEncodingBuilder()
	.add("platform", "android")
	.add("name", "bug")
	.add("subject", "XXXXXXXXXXXXXXX")
	.build();

  	Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();

  	Response response = client.newCall(request).execute();
	if (response.isSuccessful()) {
	    return response.body().string();
	} else {
	    throw new IOException("Unexpected code " + response);
	}
}

总结

通过上面的例子我们可以发现,OkHttp在很多时候使用都是很方便的,而且很多代码也有重复,因此特地整理了下面的工具类。
注意:

  • OkHttp官方文档并不建议我们创建多个OkHttpClient,因此全局使用一个。 如果有需要,可以使用clone方法,再进行自定义。这点在后面的高级教程里会提到。
  • enqueue为OkHttp提供的异步方法,入门教程中并没有提到,后面的高级教程里会有解释。
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import cn.wiz.sdk.constant.WizConstant;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response; 
 
public class OkHttpUtil {
    private static final OkHttpClient mOkHttpClient = new OkHttpClient();
    static{
        mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
    }
    /**
     * 该不会开启异步线程。
     * @param request
     * @return
     * @throws IOException
     */
    public static Response execute(Request request) throws IOException{
        return mOkHttpClient.newCall(request).execute();
    }
    /**
     * 开启异步线程访问网络
     * @param request
     * @param responseCallback
     */
    public static void enqueue(Request request, Callback responseCallback){
        mOkHttpClient.newCall(request).enqueue(responseCallback);
    }
    /**
     * 开启异步线程访问网络, 且不在意返回结果(实现空callback)
     * @param request
     */
    public static void enqueue(Request request){
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            
            @Override
            public void onResponse(Response arg0) throws IOException {
                
            }
            
            @Override
            public void onFailure(Request arg0, IOException arg1) {
                
            }
        });
    }
    public static String getStringFromServer(String url) throws IOException{
        Request request = new Request.Builder().url(url).build();
        Response response = execute(request);
        if (response.isSuccessful()) {
            String responseUrl = response.body().string();
            return responseUrl;
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }
	private static final String CHARSET_NAME = "UTF-8";
	/**
	 * 这里使用了HttpClinet的API。只是为了方便
	 * @param params
	 * @return
	 */
	public static String formatParams(List<BasicNameValuePair> params){
		return URLEncodedUtils.format(params, CHARSET_NAME);
	}
	/**
	 * 为HttpGet 的 url 方便的添加多个name value 参数。
	 * @param url
	 * @param params
	 * @return
	 */
	public static String attachHttpGetParams(String url, List<BasicNameValuePair> params){
		return url + "?" + formatParams(params);
	}
	/**
	 * 为HttpGet 的 url 方便的添加1个name value 参数。
	 * @param url
	 * @param name
	 * @param value
	 * @return
	 */
	public static String attachHttpGetParam(String url, String name, String value){
		return url + "?" + name + "=" + value;
	}
}

高级

高级属性其实用的不多,这里主要是对OkHttp github官方教程进行了翻译。
请看我的另一篇博客:OkHttp使用进阶 译自OkHttp Github官方教程

posted @ 2014-09-30 13:44  GavinCT  阅读(66641)  评论(20编辑  收藏  举报