java封装https的get、post请求

这篇具有很好参考价值的文章主要介绍了java封装https的get、post请求。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

话不多说,直接进入正题。

原生的方法,java8中全部都有文章来源地址https://www.toymoban.com/news/detail-511940.html

package com.foxconn.weixin_v2.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.stream.Collectors;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class HttpsUtils {

    public static String sendGet(String url, Map<String, String> headers, Map<String, String> body) throws Exception {
        String paramsStr = "";
        if(body!= null){
            paramsStr = body.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        }
        if (!paramsStr.isEmpty()) {
            url += "?" + paramsStr;
        }

        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        HostnameVerifier ignoreHostnameVerifier = new MyHostnameVerifier();
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, new TrustManager[]{new MyX509TrustManager1()}, new SecureRandom());
        con.setSSLSocketFactory(sslContext.getSocketFactory());
        con.setHostnameVerifier(ignoreHostnameVerifier);

        if(headers!= null){
            headers.forEach(con::setRequestProperty);
        }

        int responseCode = con.getResponseCode();
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();
    }

    public static String sendPost(String url, Map<String, String> headers, Map<String, String> data) throws Exception {
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        HostnameVerifier ignoreHostnameVerifier = new MyHostnameVerifier();
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, new TrustManager[]{new MyX509TrustManager1()}, new SecureRandom());
        con.setSSLSocketFactory(sslContext.getSocketFactory());
        con.setHostnameVerifier(ignoreHostnameVerifier);
        if(headers!= null){
            headers.forEach(con::setRequestProperty);
        }
        String paramsStr = "";
        if(data!= null){
            paramsStr = data.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        }


        con.setDoOutput(true);
        con.getOutputStream().write(paramsStr.getBytes());


        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();
    }



}
/**
 * 实现X509TrustManager接口,信任所有
 */
class MyX509TrustManager1 implements X509TrustManager {

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) {

    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) {

    }

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

/**
 * 实现HostnameVerifier接口,忽略HTTPS主机验证
 */
class MyHostnameVerifier implements HostnameVerifier {

    @Override
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
}



到了这里,关于java封装https的get、post请求的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包