OKhttp
简介
OKhttp是square公司出品的,它是一个高效的HTTP客户端,(Retrofit中的http通信实现也是基于OKhttp的)它有以下默认特性:
- HTTP/2 support allows all requests to the same host to share a socket.
- Connection pooling reduces request latency (if HTTP/2 isn’t available).
- Transparent GZIP shrinks download sizes.
- Response caching avoids the network completely for repeat requests.
基本使用
1.添加依赖
目前最新的okhttp的version是3.13.1
dependencies {
implementation 'com.squareup.okhttp3:okhttp:3.13.1'
}
2.GET方式
(1)同步请求,关键调用okhttpClient.execute()
private void GetOKhttp() {
new Thread(new Runnable() {
@Override
public void run() {
//创建OkhttpClient
OkHttpClient okHttpClient = new OkHttpClient();
//创建request
Request request = new Request.Builder()
.url("http://www.baidu.com")
.build();
//同步网络请求
try {
okhttp3.Response response = okHttpClient.newCall(request).execute();
//若成功返回
if(response.isSuccessful()){
ok_string = response.body().toString();
handler.obtainMessage(1).sendToTarget();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
(2)异步请求,关键调用okhttpClient.enqueue
private void GetOKhttp() {
//创建OkHttpClient实例
OkHttpClient okHttpClient = new OkHttpClient();
//创建Request对象
Request request = new Request.Builder()
.url("http://www.baidu.com")
.build();
//获取Call接口
okhttp3.Call call = okHttpClient.newCall(request);
//异步网络请求
call.enqueue(new okhttp3.Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
}
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
Log.i("xw", "11111:" + response.isSuccessful());
}
});
}
同步请求是在主线程中进行的,因此若网络请求耗时我们需要将其放在线程中去处理;而异步请求,因为回调方法中就是在子线程中实现的,因此无需另起线程。
3.POST请求
post请求也是有同步和异步的分别。我们这里就以异步情况为例:
private void PostOKhttp() {
//创建OkhttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//创建表单对象
FormBody.Builder builder = new FormBody.Builder();
//键值对输入
builder.add("key","123123123");
builder.add("cityname","上海");
//创建request参数,其中需要添加pos方式
Request request = new Request.Builder()
.post(builder.build())
.url("http://api.avatardata.cn/?")
.build();
//创建Call接口
okhttp3.Call call = okHttpClient.newCall(request);
//异步请求
call.enqueue(new okhttp3.Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
Log.i("xw","fail!");
}
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
Log.i("xw","sucess!" + response.code());
if (response.isSuccessful()){
}
}
});
}
post方法接收的参数是RequestBody 对象。可以传递如下几种:
FormBody对象
FormBody是RequestBody的子类。多用于传递键值对。
public final class FormBody extends RequestBody {
private static final MediaType CONTENT_TYPE = MediaType.get("application/x-www-form-urlencoded");
private final List<String> encodedNames;
private final List<String> encodedValues;
FormBody(List<String> encodedNames, List<String> encodedValues) {
JSON对象/File对象
这里关键就是在于MediaType的设置。查看源码MediaType类可以看到:
public final class MediaType {
private static final String TOKEN = "([a-zA-Z0-9-!#$%&'*+.^_`{|}~]+)";
private static final String QUOTED = "\"([^\"]*)\"";
private static final Pattern TYPE_SUBTYPE = Pattern.compile(TOKEN + "/" + TOKEN);
private static final Pattern PARAMETER = Pattern.