OkHttpClient
是一个非常高效的 HTTP 客户端库,由 Square 开发并维护。它被广泛用于 Android 开发,但也可以用于普通的 Java 应用程序。下面是如何使用 OkHttpClient 发送 HTTP 请求的一些基本示例。
1. 添加依赖
如果你使用的是 Maven,可以在 pom.xml
文件中添加以下依赖:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.10.0</version>
</dependency>
如果你使用的是 Gradle,可以在 build.gradle
文件中添加以下依赖:
implementation 'com.squareup.okhttp3:okhttp:4.10.0'
2. 创建 OkHttpClient 实例
import okhttp3.OkHttpClient;
public class Main {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
}
}
3. 发送 GET 请求
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class Main {
public static void main(String[] args) throws Exception {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://api.example.com/data")
.get() // 默认就是 GET 请求,所以这行可选
.addHeader("accept", "application/json")
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
}
}
4. 发送 POST 请求
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class Main {
public static void main(String[] args) throws Exception {
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"key\":\"value\"}");
Request request = new Request.Builder()
.url("https://api.example.com/data")
.post(body)
.addHeader("content-type", "application/json")
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
}
}
5. 异步发送请求
OkHttpClient 也支持异步请求,这对于避免阻塞 UI 线程尤其有用。
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class Main {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://api.example.com/data")
.get()
.addHeader("accept", "application/json")
.build();
client.newCall(request).enqueue(new okhttp3.Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
});
}
}
以上示例演示了如何使用 OkHttpClient 发送 GET 和 POST 请求,以及如何处理响应。你可以根据需要调整这些代码以适应不同的情况。如果你需要更高级的功能,比如设置超时、重试策略等,可以参考 OkHttpClient 的官方文档。