文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Java原生HttpClient的使用详解

2024-04-02 19:55

关注

提到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.测试

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

以上就是Java原生HttpClient的使用详解的详细内容,更多关于Java HttpClient的资料请关注编程网其它相关文章!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     801人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     348人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     311人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     432人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     220人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯