使用 Java 11+ HttpClient 设置请求参数
从Java 11开始,Java自带的HttpClient
可以方便地发送HTTP请求。以下是如何设置GET和POST请求参数的示例:
GET 请求
对于GET请求,参数通常通过URL拼接的方式传递:
java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Java11HttpClientExample {
public static void main(String[] args) {
String baseUrl = "https://api.example.com/data";
String param1 = "value1";
String param2 = "value2";
// 构建带参数的URL
String fullUrl = baseUrl + "?param1=" + param1 + "¶m2=" + param2;
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(fullUrl))
.GET()
.build();
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Response: " + response.body());
} catch (Exception e) {
e.printStackTrace();
}
}
}
POST 请求
对于POST请求,参数可以通过请求体传递:
java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Java11HttpClientPostExample {
public static void main(String[] args) {
String url = "https://api.example.com/data";
String jsonBody = "{\"param1\":\"value1\", \"param2\":\"value2\"}";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonBody))
.build();
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Response: " + response.body());
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用 Apache HttpClient 设置请求参数
Apache HttpClient 是一个功能强大的第三方库,可以用来发送HTTP请求。以下是如何设置GET和POST请求参数的示例:
GET 请求
对于GET请求,可以使用URIBuilder
来构建带参数的URL:
java
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.net.URI;
public class ApacheHttpClientExample {
public static void main(String[] args) {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
URI uri = new URIBuilder()
.setScheme("http")
.setHost("example.com")
.setPath("/api/data")
.setParameter("param1", "value1")
.setParameter("param2", "value2")
.build();
HttpGet httpGet = new HttpGet(uri);
httpGet.setHeader("Content-Type", "application/json");
httpClient.execute(httpGet);
} catch (Exception e) {
e.printStackTrace();
}
}
}
POST 请求
对于POST请求,可以通过HttpPost
和StringEntity
来设置请求体:
java
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class ApacheHttpClientPostExample {
public static void main(String[] args) {
String url = "https://api.example.com/data";
String jsonBody = "{\"param1\":\"value1\", \"param2\":\"value2\"}";
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/json");
StringEntity entity = new StringEntity(jsonBody, "UTF-8");
httpPost.setEntity(entity);
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("Response: " + responseBody);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
注意事项
-
参数编码 :在设置请求参数时,确保对参数值进行适当的编码,以避免特殊字符导致的问题。可以使用
java.net.URLEncoder
来对参数值进行编码。 -
请求头设置 :根据目标API的要求,设置适当的请求头,例如
User-Agent
、Content-Type
等。 -
错误处理:在发送请求时,添加适当的错误处理逻辑,以确保程序的健壮性。
通过上述示例代码,你可以使用 Java 11+ HttpClient 或 Apache HttpClient 设置HTTP请求参数。无论是GET请求还是POST请求,都可以通过构建适当的请求对象来实现。希望这些示例能帮助你在开发中更好地设置HTTP请求参数。