栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java后台直接调用第三方https请求

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java后台直接调用第三方https请求

项目场景:

没有页面需要在java接口中直接调用第三方https请求,忽略证书


解决方案:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class HttpsClient {
    private static final Logger logger = LoggerFactory.getLogger(HttpsClient.class);
    private static final class DefaultTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

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

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

    public static HttpsURLConnection getHttpsURLConnection(String uri, String method) throws IOException {
        SSLContext ctx = null;
        try {
            ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        SSLSocketFactory ssf = ctx.getSocketFactory();

//        URL url = new URL(uri);
        URL url= new URL(null, uri, new sun.net.www.protocol.https.Handler());
        HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
        httpsConn.setSSLSocketFactory(ssf);
        httpsConn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
        httpsConn.setRequestMethod(method);
        httpsConn.setDoInput(true);
        httpsConn.setDoOutput(true);
        httpsConn.setConnectTimeout(4000);
        if(method.equals("POST")){
            httpsConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        }
        return httpsConn;
    }

    public static byte[] getBytesFromStream(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] kb = new byte[1024];
        int len;
        while ((len = is.read(kb)) != -1) {
            baos.write(kb, 0, len);
        }
        byte[] bytes = baos.toByteArray();
        baos.close();
        is.close();
        return bytes;
    }

    private static void setBytesToStream(OutputStream os, byte[] bytes) throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        byte[] kb = new byte[1024];
        int len;
        while ((len = bais.read(kb)) != -1) {
            os.write(kb, 0, len);
        }
        os.flush();
        os.close();
        bais.close();
    }

    private static String doGet(String uri) {
        try {
            logger.info("https的Get请求链接为: "+uri);
            HttpsURLConnection httpsConn = getHttpsURLConnection(uri, "GET");
            return new String(getBytesFromStream(httpsConn.getInputStream()));
        } catch (IOException e) {
            logger.error("http的Get请求出现异常:", e.getCause());
        }
        return null;
    }

    public static String doJsonPost(String uri, String data) {
        try {
            logger.info("https的POST请求地址为: "+uri);
            logger.info("https的POST请求参数为: "+data);
            HttpsURLConnection httpsConn = getHttpsURLConnection(uri, "POST");
            setBytesToStream(httpsConn.getOutputStream(), data.getBytes("utf-8"));
            String result = new String(getBytesFromStream(httpsConn.getInputStream()));
            logger.info("https的POST请求结果为: "+result);
            return result;
        } catch (IOException e){
            logger.error("http的Posy请求出现异常:", e);
        }
        return null;
    }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1019931.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号