Android笔记
——Okhttp
【若对该知识点有更多想了解的,欢迎私信博主~~】
依赖框架:Okhttp3
一:优势及作用
- 支持HTTP/2,允许所有同一个主机地址的请求共享同一个socket连接
- 连接池减少请求延时
- 透明的GZIP压缩减少响应数据的大小
- 缓存响应内容,避免一些完全重复的请求
二:Okhttp3的配置
-
在app的 build.gradle中dependencies中添加
implementation 'com.squareup.okhttp3:okhttp:3.12.1' debugImplementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'
三:使用
import android.os.Handler;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class HttpTool {
public static void myPost(final String url, final String json, final NetBack netBack) {
final Handler handler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
try {
//构造RequestBody:携带要填充的数据 以及 数据格式
RequestBody body = RequestBody.create(
MediaType.parse("application/json;charset=utf-8"), json
);
//构造Request请求对象:url()--请求的地址,post()--post方法,默认get方法
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
//构造OkHttpClient发起请求:newCall()--发起请求
//并构造Response接收返回结果:execute()--执行接收
Response response = new OkHttpClient()
.newCall(request)
.execute();
//获取Response返回的内容
final String rjson = response.body().string();
//返回结果
handler.post(new Runnable() {
@Override
public void run() {
netBack.OnSuccess(rjson);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
public interface NetBack {
void OnSuccess(String rjson);
}
参考资料:
- https://www.jianshu.com/p/da4a806e599b
- https://github.com/square/okhttp