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的一些基本用法,還有更多的功能和選項可以根據具體需求進行使用。