OkHttp是一个开源的HTTP客户端库,用于发送网络请求和处理响应。它提供了简单、高效、灵活和安全的API,可以用于Android和Java应用程序。
以下是OkHttp的一些常用用法:
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();
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();
Request request = new Request.Builder()
.url("https://example.com/api")
.header("Authorization", "Bearer token")
.build();
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) {
// 处理错误
}
});
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.build();
以上只是OkHttp的一些基本用法,还有更多的功能和选项可以根据具体需求进行使用。