📅  最后修改于: 2023-12-03 15:03:21.587000             🧑  作者: Mango
OkHttp3是一个高效、稳定、易用的Java/Android HTTP客户端库,它基于HTTP/2协议,并允许使用HTTP/1.1和WebSocket。OkHttp3是Square公司的主要项目,它为Android和Java应用程序提供了简单、安全、可靠的HTTP交互。
添加依赖
implementation 'com.squareup.okhttp3:okhttp:3.14.9'
创建OkHttpClient实例
OkHttpClient client = new OkHttpClient();
构建一个HTTP请求
String url = "https://www.example.com/";
Request request = new Request.Builder()
.url(url)
.build();
同步请求
try (Response response = client.newCall(request).execute()) {
String responseBody = response.body().string();
}
异步请求
client.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override public void onResponse(Call call, Response response) throws IOException {
String responseBody = response.body().string();
}
});
使用拦截器
Interceptor interceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Log.d(TAG, String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
Log.d(TAG, String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
};
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.build();
OkHttp3是一个高效、稳定、易用的Java/Android HTTP客户端库,它具有许多优秀的特性和强大的功能。如果你需要一个稳定、高性能的HTTP客户端库,那么OkHttp3将是一个不错的选择。