httpclient包:

commons.httpclient-3.1.jar

 设置允许访问https请求:

package com.zyjc.cdss.common.utils;

import com.zyjc.cdss.common.exception.BizException;
import com.zyjc.cdss.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

@Slf4j
public class HttpUtil {

    public static String doPost(
            String host,
            String path,
            String json,
            String charset,
            String contentType) {
        SecureProtocolSocketFactory factory = getSecureProtocolSocketFactory();
        Protocol.registerProtocol("https", new Protocol("https", factory, 443));

        PostMethod method = new PostMethod(host + path);
        HttpClient httpClient = new HttpClient();
        try {
            RequestEntity entity = new StringRequestEntity(json, contentType, charset);
            method.setRequestEntity(entity);
            httpClient.executeMethod(method);
            log.info("request url : " + method.getURI().toString());
            InputStream in = method.getResponseBodyAsStream();
            StringBuffer sb = new StringBuffer();
            InputStreamReader inputStreamReader = new InputStreamReader(in, charset);
            char[] b = new char[4096];
            for (int n; (n = inputStreamReader.read(b)) != -1; ) {
                sb.append(new String(b, 0, n));
            }
            String returnStr = sb.toString();
            return returnStr;

        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("请求失败 : " + e.getMessage());
        } finally {
            method.releaseConnection();
        }
    }


    /**
     * 忽略服务器端证书链的认证
     *
     * @return
     */
    private static TrustManager getTrustManagers() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

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

            }

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

    private static SecureProtocolSocketFactory getSecureProtocolSocketFactory() {
        return new SecureProtocolSocketFactory() {
            private SSLContext sslContext = null;

            private SSLContext creatEasySSLContext() {
                try {
                    SSLContext context = SSLContext.getInstance("SSL");
                    context.init(null, new TrustManager[]{
                            getTrustManagers()
                    }, null);
                    return context;
                } catch (Exception e) {
                    throw new BizException("获取SSL上下文异常");
                }
            }

            private SSLContext getSSLContext() {
                if (this.sslContext == null) {
                    this.sslContext = creatEasySSLContext();
                }
                return this.sslContext;
            }

            @Override
            public Socket createSocket(String s, int i, InetAddress inetAddress, int i1) throws IOException, UnknownHostException {
                return getSSLContext().getSocketFactory().createSocket(s, i, inetAddress, i1);
            }

            @Override
            public Socket createSocket(String s, int i, InetAddress inetAddress, int i1, HttpConnectionParams httpConnectionParams) throws IOException, UnknownHostException, ConnectTimeoutException {
                if (httpConnectionParams == null) {
                    throw new BizException("param may not be null");
                }
                int timeout = httpConnectionParams.getConnectionTimeout();
                if (timeout == 0) {
                    return createSocket(s, i, inetAddress, i1);
                } else  {
                    return ControllerThreadSocketFactory.createSocket(this, s, i, inetAddress, i1, timeout);
                }
            }

            @Override
            public Socket createSocket(String s, int i) throws IOException, UnknownHostException {
                return getSSLContext().getSocketFactory().createSocket(s, i);
            }

            @Override
            public Socket createSocket(Socket socket, String s, int i, boolean b) throws IOException, UnknownHostException {
                return getSSLContext().getSocketFactory().createSocket(socket, s, i, b);
            }
        };
    }
}

请求案例:

String responseJsonStr = HttpUtil.doPost(
                "https://192.176.1.121:8909",
                "/your/interface/api",
                "JSON.toJSONString(body内容)",
                Charsets.UTF_8.name(),
                MediaType.APPLICATION_JSON_UTF8_VALUE);

 

posted on 2021-06-01 15:19  miaoying  阅读(1722)  评论(0编辑  收藏  举报