httpclient5 发送get请求 带参数
时间: 2023-08-31 20:05:14 浏览: 144
HTTP GET/POST传递参数
5星 · 资源好评率100%
HttpClient5 可以通过以下步骤发送带参数的 GET 请求:
1. 创建 HttpClient 对象。
```java
HttpClient httpClient = HttpClient.newHttpClient();
```
2. 创建 HttpRequest 对象,设置请求方法为 GET,设置请求 URL,设置请求参数。
```java
String url = "http://example.com/api";
Map<String, String> params = new HashMap<>();
params.put("key1", "value1");
params.put("key2", "value2");
String query = params.entrySet().stream()
.map(entry -> entry.getKey() + "=" + entry.getValue())
.collect(Collectors.joining("&"));
HttpRequest httpRequest = HttpRequest.newBuilder()
.uri(URI.create(url + "?" + query))
.GET()
.build();
```
3. 发送请求并获取响应。
```java
HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
String responseBody = httpResponse.body();
```
完整示例代码如下:
```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
HttpClient httpClient = HttpClient.newHttpClient();
String url = "http://example.com/api";
Map<String, String> params = new HashMap<>();
params.put("key1", "value1");
params.put("key2", "value2");
String query = params.entrySet().stream()
.map(entry -> entry.getKey() + "=" + entry.getValue())
.collect(Collectors.joining("&"));
HttpRequest httpRequest = HttpRequest.newBuilder()
.uri(URI.create(url + "?" + query))
.GET()
.build();
HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
String responseBody = httpResponse.body();
System.out.println(responseBody);
}
}
```
阅读全文