Java原生HttpClient的使用详解

作者:农民工老王 时间:2022-06-04 16:29:49 

提到Java发送HTTP请求,大家首先想到的是用apache的HttpClient,或者squareup的OkHttp。而在Java11之前,原生Java对此的支持还是比较差的,虽然可以HttpURLConnection、URLConnection、Socket等自带的类发送请求,但是操作比较复杂。直到Java11发布,Java本身也自带了HttpClient。自2020年初,我就在开发中广泛使用了这一新特性,感觉使用体验也还可以。现总结成博客,供大家参考。

1.信任证书管理类

package cn.wja.component;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;

class MyX509TrustManager implements X509TrustManager {
   @Override
   public void checkClientTrusted(X509Certificate[] x509Certificates, String s)  {
   }

@Override
   public void checkServerTrusted(X509Certificate[] x509Certificates, String s)  {
   }

@Override
   public X509Certificate[] getAcceptedIssuers() {
       return null;
   }

public static TrustManager[] getTrustManagers() {
       TrustManager[] trustAllCertificates = {new MyX509TrustManager()};
       return trustAllCertificates;
   }
}

2.HttpClient类

package cn.wja.component;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.TrustManager;
import java.net.http.HttpClient;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Duration;

public class MyHttpClient {
   static public HttpClient getClient() throws NoSuchAlgorithmException, KeyManagementException {
       TrustManager[] trustManagers = MyX509TrustManager.getTrustManagers();
       var timeoutInSeconds = 60;
       SSLParameters sslParams = new SSLParameters();
       sslParams.setEndpointIdentificationAlgorithm("");
       SSLContext sc = SSLContext.getInstance("SSL");
       //取消主机名验证
       System.setProperty("jdk.internal.httpclient.disableHostnameVerification", "true");
       sc.init(null, trustManagers, new SecureRandom());
       return HttpClient.newBuilder()
               .connectTimeout(Duration.ofMillis(timeoutInSeconds * 1000))
               .sslContext(sc)
               .sslParameters(sslParams)
               .followRedirects(HttpClient.Redirect.NEVER)
               .version(HttpClient.Version.HTTP_2)
               .build();
   }
}

3.发送请求工具类

package cn.wja.util;

import cn.wja.component.MyHttpClient;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

import static java.nio.charset.StandardCharsets.UTF_8;

public class HttpUtils {

public static HttpResponse<String> sendGet(String urlStr, String cookieStr) throws Exception {
       HashMap<String, String> hashMap = new HashMap<>();
       hashMap.put("Cookie",cookieStr);
       return sendGet(urlStr,hashMap);
   }

public static HttpResponse<String> sendGet(String urlStr, Map<String,String> headers) throws KeyManagementException, NoSuchAlgorithmException, IOException, InterruptedException {
       HttpClient client = MyHttpClient.getClient();
       HttpRequest.Builder reqBuilder = getReqBuilder(urlStr);
       reqBuilder.GET();
       for (String key:headers.keySet()){
           reqBuilder.header(key, headers.get(key));
       }
       HttpRequest request = reqBuilder.build();
       HttpResponse<String> result = client.send(request, HttpResponse.BodyHandlers.ofString(UTF_8));
       return result;
   }

private static HttpResponse<String> sendPost(String contentType, String urlStr, String bodyStr, String cookieStr) throws Exception {
       HttpClient client = MyHttpClient.getClient();
       HttpRequest.Builder reqBuilder = getReqBuilder(urlStr);
       HttpRequest.BodyPublisher bodyPublisher = HttpRequest.BodyPublishers.ofString(bodyStr);
       reqBuilder.header("Content-Type", contentType)
               .POST(bodyPublisher)
               .header("Cookie", cookieStr);
       HttpRequest request = reqBuilder.build();
       HttpResponse<String> result = client.send(request, HttpResponse.BodyHandlers.ofString(UTF_8));
       return result;
   }

public static HttpResponse<String> sendFormPost(String urlStr, String formStr, String cookieStr) throws Exception {
       return sendPost("application/x-www-form-urlencoded;charset=utf-8", urlStr, formStr, cookieStr);
   }

public static HttpResponse<String> sendJsonPost(String urlStr, String jsonStr, String cookieStr) throws Exception {
       return sendPost("application/json;charset=utf-8", urlStr, jsonStr, cookieStr);
   }

public static HttpRequest.Builder getReqBuilder(String urlStr) {
       return HttpRequest.newBuilder()
               .uri(URI.create(urlStr))
               .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:96.0) Gecko/20100101 Firefox/96.0");
   }
}

4.测试

Java原生HttpClient的使用详解

测试表明,通过调用工具类方法,可以直接发送GET请求和带Form表单/Json的POST请求。如果您要发送其他形式的HTTP请求,也可以参照上述代码自行实现。

来源:https://tomcat.blog.csdn.net/article/details/123157836

标签:Java,原生,HttpClient
0
投稿

猜你喜欢

  • android实现通知栏下载更新app示例

    2022-01-06 01:58:56
  • java编写简单的ATM存取系统

    2023-06-28 07:50:33
  • 解决Java中socket使用getInputStream()阻塞问题

    2022-06-16 14:33:14
  • C#中DataGridView常用操作实例小结

    2023-03-09 23:55:16
  • Android实现简单的分批加载ListView

    2023-10-28 14:49:21
  • Android实现语音合成与识别功能

    2023-10-01 01:41:00
  • Java全面详细讲解逻辑控制的使用

    2021-10-16 12:48:42
  • Java毕业设计实战之教室预订管理系统的实现

    2023-03-03 20:38:11
  • 浅谈JVM中的JOL

    2022-10-06 15:44:49
  • 细谈java同步之JMM(Java Memory Model)

    2023-11-23 13:09:33
  • 浅谈Spring @Async异步线程池用法总结

    2021-09-11 07:12:08
  • gson对象序列化的示例

    2023-11-25 08:54:28
  • java学习之利用TCP实现的简单聊天示例代码

    2021-07-13 00:43:18
  • 手把手教你搭建SpringMVC框架——最小化配置

    2022-02-16 02:38:16
  • java + dom4j.jar提取xml文档内容

    2023-11-29 03:55:10
  • Android 3D旋转动画效果实现分解

    2022-11-14 17:53:00
  • java.net.ConnectException: Connection refused问题解决办法

    2023-11-28 18:49:52
  • C# 反射与 Quartz 实现流程处理详情

    2022-11-11 09:11:07
  • 解决grails服务端口冲突的办法(grails修改端口号)

    2023-09-12 01:00:03
  • SpringIOC框架的简单实现步骤

    2021-10-28 21:44:35
  • asp之家 软件编程 m.aspxhome.com