这篇文章主要介绍“Java原生HttpClient怎么使用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Java原生HttpClient怎么使用”文章能帮助大家解决问题。
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; } }
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(); } }
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"); } }
测试表明,通过调用工具类方法,可以直接发送GET请求和带Form表单/Json的POST请求。如果您要发送其他形式的HTTP请求,也可以参照上述代码自行实现。
关于“Java原生HttpClient怎么使用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。