使用JDK11字段http客户端发送http请求
请求示例
使用JDK11字段http客户端发送httpGET请求方式 代码示例:
HttpClient client;
HttpRequest httpRequest;
String result;
String request;
String url = "你要访问的url地址";
// 生成Http客户端请求对象
client = HttpClient.newBuilder()
// 设置连接超时时长为20秒
.connectTimeout(Duration.ofSeconds(20))
.build();
//创建请求对象
httpRequest = HttpRequest
.newBuilder(URI.create(url))
.header("Content-Type", "application/json;charset=utf-8")
//这里有多个请求头可以点header多次 我这里是两个请求头参数
.header("token", "token")
.GET()
//请求超时时间20秒
.timeout(Duration.ofSeconds(20))
.build();
HttpResponse.BodyHandler<String> inputStreamBodyHandler = HttpResponse.BodyHandlers.ofString();
CompletableFuture<HttpResponse<String>> httpResponseCompletableFuture = client.sendAsync(httpRequest, inputStreamBodyHandler);
HttpResponse<String> stringHttpResponse = httpResponseCompletableFuture.get();
result = stringHttpResponse.body();
//你后续的处理操作
POST请求方式下期补充