Java 11引入了新的HTTP客户端API,可以使用它来发送HTTP请求。下面是使用Java 11 HTTP客户端为POST请求定义多个参数的步骤:
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.HashMap;
import java.util.Map;
HttpClient client = HttpClient.newHttpClient();
Map<String, String> params = new HashMap<>();
params.put("param1", "value1");
params.put("param2", "value2");
String url = "http://example.com/api";
URI uri = URI.create(url);
String requestBody = params.entrySet().stream()
.map(entry -> entry.getKey() + "=" + entry.getValue())
.collect(Collectors.joining("&"));
HttpRequest request = HttpRequest.newBuilder()
.uri(uri)
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(BodyPublishers.ofString(requestBody))
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
int statusCode = response.statusCode();
String responseBody = response.body();
HttpHeaders headers = response.headers();
以上代码将创建一个包含多个参数的POST请求,并将参数以"key=value"的形式拼接到请求体中。然后发送请求并获取响应,包括状态码、响应体和响应头。
对于Java 11 HTTP客户端的更多信息和用法,请参考腾讯云的相关产品和文档:
领取专属 10元无门槛券
手把手带您无忧上云