Jdk11新增HttpClient客户端,发送get请求
-
JDK11新增HttpClient,⽀持 HTT/1.1, HTTP/2
-
常⽤类和接⼝讲解
HttpClient.Builder
HttpClient 构建⼯具类
HttpRequest.Builder
HttpRequest 构建⼯具类
HttpRequest.BodyPublisher
将java 对象转换为可发送的HTTP request body字节流, 如form表单提交
HttpResponse.BodyHandler
处理接收到的 Response Body
- 发送get请求案例
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class Main {
public static void main(String[] args) throws Exception {
testGet();
}
private static final String targetUrl = "http://api.xdclass.net/pub/api/v1/web/all_category";
private static final URI uri = URI.create(targetUrl);
private static final void testGet() {
//var httpClient = HttpClient.newHttpClient(); // 方式1
//设置建立连接的超时 connect timeout
var httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofMillis(5000)).build(); // 方式2
var request = HttpRequest.newBuilder().timeout(Duration.ofMillis(3000))
.header("key1", "v1")
.header("key2", "v2")
.uri(uri).build();
try {
var response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
} catch (Exception e) {
e.printStackTrace();
}
}
}