温馨提示×

okhttp的用法有哪些

小亿
114
2023-08-01 15:56:43
栏目: 编程语言

OkHttp是一个开源的HTTP客户端库,用于发送网络请求和处理响应。它提供了简单、高效、灵活和安全的API,可以用于Android和Java应用程序。

以下是OkHttp的一些常用用法:

  1. 发送GET请求:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://example.com/api")
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
  1. 发送POST请求:
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new FormBody.Builder()
.add("username", "username")
.add("password", "password")
.build();
Request request = new Request.Builder()
.url("https://example.com/api")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
  1. 设置请求头:
Request request = new Request.Builder()
.url("https://example.com/api")
.header("Authorization", "Bearer token")
.build();
  1. 异步请求:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://example.com/api")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseData = response.body().string();
// 处理响应
}
@Override
public void onFailure(Call call, IOException e) {
// 处理错误
}
});
  1. 设置超时时间:
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.build();

以上只是OkHttp的一些基本用法,还有更多的功能和选项可以根据具体需求进行使用。

0