深圳全胜专业网站建设,医药公司网站建设备案,企业网站推广建议,网站变成了百度推广前言
每种编程语言里最常用的库恐怕是Http请求库了#xff0c;如python里的requests包#xff0c;nodejs里的request模块。 在Java世界里#xff0c;也是百花齐放#xff0c;山头林立。常用的有#xff1a;
HttpURLConnection: 最早的JDK提供的类Java 11提供的HttpClien…前言
每种编程语言里最常用的库恐怕是Http请求库了如python里的requests包nodejs里的request模块。 在Java世界里也是百花齐放山头林立。常用的有
HttpURLConnection: 最早的JDK提供的类Java 11提供的HttpClientApache HttpComponents项目中的HTTPClientSquare提供的OkHttpClientSpring 自带的WebClient
Apache HttpComponents
该组件提供了两个核心类
HttpCore: 更底层的传输处理类HttpClient基于HttpCore实现的HTTP-compliant 处理类
JDK 11 HTTP Client使用举例
Post同步的json数据
public void invokePost() {try {String requestBody prepareRequest();HttpClient client HttpClient.newHttpClient();HttpRequest request HttpRequest.newBuilder().uri(URI.create(https://reqbin.com/echo/post/json)).POST(HttpRequest.BodyPublishers.ofString(requestBody)).header(Accept, application/json).build();HttpResponseString response client.send(request, HttpResponse.BodyHandlers.ofString());System.out.println(response.body());} catch (IOException | InterruptedException e) {e.printStackTrace();}}private String prepareRequest() throws JsonProcessingException {var values new HashMapString, String() {{put(Id, 12345);put(Customer, Roger Moose);put(Quantity, 3);put(Price,167.35);}};var objectMapper new ObjectMapper();String requestBody objectMapper.writeValueAsString(values);return requestBody;}
发送异步请求
public void invoke() throws URISyntaxException {HttpClient client HttpClient.newBuilder().version(Version.HTTP_2).followRedirects(Redirect.NORMAL).build();HttpRequest request HttpRequest.newBuilder().uri(new URI(URLConstants.URL)).GET().header(URLConstants.API_KEY_NAME, URLConstants.API_KEY_VALUE).timeout(Duration.ofSeconds(10)).build();client.sendAsync(request, BodyHandlers.ofString()).thenApply(HttpResponse::body).thenAccept(System.out::println).join();}HTTP Client包装库
cVurl cVurl is an open-source wrapper for the Java HTTP client. It is written in Java 11 and can be used with any JDK 11.0.2 or newer. public void cVurl() {CVurl cVurl new CVurl();//POSTResult result cVurl.post(https://api.imgflip.com/caption_image).queryParams(Map.of(template_id, 112126428,username, test-user,password, 123test321,text0, text0,text1, text1)).asObject(Result.class);System.out.println(CVurl POST: result);
}它支持Compression、Multipart、Form data这些Java 11 HttpClient不具备的特性。
Avaje-HTTP
Fluid API for building URLs and payloadJSON marshaling using Avaje Jsonb/Jackson/GsonLight Feign-style interfaces via annotation processing.Request/Response InterceptionAuthorization via Basic Auth or OAuth Bearer TokensAsync and sync API
个人建议
在实际项目中设计符合自身项目需求的HTTP client接口并基于JDK 11 HTTP client实现独立于任何上述库。
参考链接
https://github.com/corese4rch/cvurlhttps://github.com/avaje/avaje-http/tree/masterhttps://reflectoring.io/comparison-of-java-http-clients/