1、引入Maven依赖
<!--okhttp3 依赖-->
<dependency>
<groupId>***.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.3</version>
</dependency>
2、发起请求 (同步)
2.1、GET请求
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.example.***/api/resource?q=123123")
.header("token", "qweqweasd123123123")
.build();
try {
Response response = client.newCall(request).execute();
if (response.isSu***essful()) {
String responseBody = response.body().string();
System.out.println(responseBody);
} else {
System.out.println("请求失败,错误码:" + response.code());
}
} catch (IOException e) {
e.printStackTrace();
}
GET 请求需要传递 application/json
参数
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
String jsonBody = "{\"key\": \"value\"}";
// 创建请求体
RequestBody requestBody = RequestBody.create(jsonBody, mediaType);
// 创建GET请求并携带请求体
Request request = new Request.Builder()
.url("http://example.***/api/endpoint")
.get()
.header("Content-Type", "application/json")
.method("GET", requestBody)
.build();
try {
// 发送请求并获取响应
Response response = client.newCall(request).execute();
// 处理响应...
} catch (IOException e) {
e.printStackTrace();
}
2.2、POST请求
String jsonData = "{\"name\": \"lizr\"}";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.example.***/api/resource")
.post(RequestBody.create(jsonData.getBytes(), MediaType.parse("application/json")))
.header("token", "qweqweasd123123123")
.build();
try {
Response response = client.newCall(request).execute();
if (response.isSu***essful()) {
String responseBody = response.body().string();
System.out.println(responseBody);
} else {
System.out.println("请求失败,错误码:" + response.code());
}
} catch (IOException e) {
e.printStackTrace();
}
2.3、PUT请求
String jsonData = "{\"name\": \"lizr\"}";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.example.***/api/resource")
.put(RequestBody.create(jsonData.getBytes(), MediaType.parse("application/json")))
.header("token", "qweqweasd123123123")
.build();
try {
Response response = client.newCall(request).execute();
if (response.isSu***essful()) {
String responseBody = response.body().string();
System.out.println(responseBody);
} else {
System.out.println("请求失败,错误码:" + response.code());
}
} catch (IOException e) {
e.printStackTrace();
}
2.4、DELETE请求
String jsonData = "{\"name\": \"lizr\"}";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.example.***/api/resource")
.delete(RequestBody.create(jsonData.getBytes(), MediaType.parse("application/json")))
.header("token", "qweqweasd123123123")
.build();
try {
Response response = client.newCall(request).execute();
if (response.isSu***essful()) {
String responseBody = response.body().string();
System.out.println(responseBody);
} else {
System.out.println("请求失败,错误码:" + response.code());
}
} catch (IOException e) {
e.printStackTrace();
}
3、发起请求 (异步)
3.1、GET请求
OkHttpClient client = new OkHttpClient();
String url = "https://example.***/api/user";
Request request = new Request.Builder()
.url(url)
.header("token", "qweqweasd123123123")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
// 处理响应数据
String responseBody = response.body().string();
System.out.println(responseBody);
}
@Override
public void onFailure(Call call, IOException e) {
// 处理请求失败情况
e.printStackTrace();
}
});
3.2、POST请求
OkHttpClient client = new OkHttpClient();
String url = "https://example.***/api/user";
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
String requestBody = "{\"username\":\"john\", \"password\":\"123456\"}";
RequestBody body = RequestBody.create(mediaType, requestBody);
Request request = new Request.Builder()
.url(url)
.post(body)
.header("token", "qweqweasd123123123")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
// 处理响应数据
String responseBody = response.body().string();
System.out.println(responseBody);
}
@Override
public void onFailure(Call call, IOException e) {
// 处理请求失败情况
e.printStackTrace();
}
});
3.3、PUT请求
OkHttpClient client = new OkHttpClient();
String url = "https://example.***/api/user";
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
String requestBody = "{\"username\":\"john\", \"password\":\"123456\"}";
RequestBody body = RequestBody.create(mediaType, requestBody);
Request request = new Request.Builder()
.url(url)
.put(body)
.header("token", "qweqweasd123123123")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
// 处理响应数据
String responseBody = response.body().string();
System.out.println(responseBody);
}
@Override
public void onFailure(Call call, IOException e) {
// 处理请求失败情况
e.printStackTrace();
}
});
3.4、DELETE请求
OkHttpClient client = new OkHttpClient();
String url = "https://example.***/api/user";
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
String requestBody = "{\"username\":\"john\", \"password\":\"123456\"}";
RequestBody body = RequestBody.create(mediaType, requestBody);
Request request = new Request.Builder()
.url(url)
.delete(body)
.header("token", "qweqweasd123123123")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
// 处理响应数据
String responseBody = response.body().string();
System.out.println(responseBody);
}
@Override
public void onFailure(Call call, IOException e) {
// 处理请求失败情况
e.printStackTrace();
}
});
4、连接池
可以使用连接池来管理和复用HTTP和HTTPS连接,以提高性能和效率
// 创建连接池对象
ConnectionPool connectionPool = new ConnectionPool(5, 10, TimeUnit.MINUTES);
// 创建OkHttpClient并设置连接池
OkHttpClient client = new OkHttpClient.Builder()
.connectionPool(connectionPool)
.build();
// 创建请求对象
Request request = new Request.Builder()
.url("http://www.example.***")
.build();
try {
// 发送请求并获取响应
Response response = client.newCall(request).execute();
if (response.isSu***essful()) {
String responseBody = response.body().string();
System.out.println(responseBody);
} else {
System.out.println("请求失败,错误码:" + response.code());
}
} catch (IOException e) {
e.printStackTrace();
}
上述代码中,通过创建ConnectionPool对象,并将其设置到OkHttpClient中,从而启用了连接池功能。ConnectionPool的构造函数接受三个参数:maxIdleConnections、keepAliveDuration和timeUnit,用于配置连接池的最大空闲连接数、连接保持时间以及时间单位。
连接池会自动管理和复用连接,适当地回收和关闭空闲的连接。这样可以避免频繁地创建和关闭连接,提高性能和效率,特别是在多次请求同一主机时。
合理地设置连接池参数非常重要,以符合你的实际需求。可以根据并发请求的数量、目标服务器的负载能力以及网络环境等因素来调整连接池的大小和保持时间。
有关更多详细信息和高级用法,建议参考 okhttp3 的官方文档或其他相关资料。