Java中使用 okhttp3 发送 Post 和 Get 请求
一、引入okhttp3的依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>
二、编写代码
public static JSONObject sendPostRequest(String url, Map<String, String> params) throws IOException {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build();
RequestBody requestBody;
if (params != null && !params.isEmpty()) {
FormBody.Builder formBuilder = new FormBody.Builder();
for (Map.Entry<String, String> entry : params.entrySet()) {
formBuilder.add(entry.getKey(), entry.getValue());
}
requestBody = formBuilder.build();
} else {
requestBody = RequestBody.create("", null);
}
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
String data = Objects.requireNonNull(response.body()).string();
return new JSONObject(data);
} else {
throw new IOException("Unexpected code " + response);
}
}
}
public static JSONObject sendGetRequest(String url, Map<String, String> params) throws IOException {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build();
String fullUrl = buildUrlWithParams(url, params);
Request request = new Request.Builder()
.url(fullUrl)
.get()
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
String data = Objects.requireNonNull(response.body()).string();
return new JSONObject(data);
} else {
throw new IOException("Unexpected code " + response);
}
}
}
private static String buildUrlWithParams(String url, Map<String, String> params) {
if (params == null || params.isEmpty()) {
return url;
}
StringBuilder urlBuilder = new StringBuilder(url);
if (!url.contains("?")) {
urlBuilder.append("?");
} else if (!url.endsWith("&") && !url.endsWith("?")) {
urlBuilder.append("&");
}
try {
for (Map.Entry<String, String> entry : params.entrySet()) {
urlBuilder.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8.name()));
urlBuilder.append("=");
urlBuilder.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.name()));
urlBuilder.append("&");
}
} catch (IOException e) {
throw new RuntimeException("Error encoding URL parameters", e);
}
urlBuilder.setLength(urlBuilder.length() - 1);
return urlBuilder.toString();
}
三、调用示例
public static void main(String[] args) {
String postUrl = "https://example.com/api";
String getUrl = "https://example.com/api";
Map<String, String> params = Map.of(
"param1", "value1",
"param2", "value2"
);
try {
JSONObject postResponse = sendPostRequest(postUrl, params);
System.out.println("POST Response: " + postResponse.toString());
} catch (IOException e) {
e.printStackTrace();
}
try {
JSONObject getResponse = sendGetRequest(getUrl, params);
System.out.println("GET Response: " + getResponse.toString());
} catch (IOException e) {
e.printStackTrace();
}
try {
JSONObject postResponseNoParams = sendPostRequest(postUrl, null);
System.out.println("POST Response without params: " + postResponseNoParams.toString());
} catch (IOException e) {
e.printStackTrace();
}
try {
JSONObject getResponseNoParams = sendGetRequest(getUrl, null);
System.out.println("GET Response without params: " + getResponseNoParams.toString());
} catch (IOException e) {
e.printStackTrace();
}
}