zoukankan      html  css  js  c++  java
  • http、https请求代码示例

       代码清单,供参考:

    MyX509TrustManager.java
    package utils;
    
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import javax.net.ssl.X509TrustManager;
    
    public class MyX509TrustManager implements X509TrustManager {
    
        /*
         * (non-Javadoc)
         * 
         * @see
         * javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.
         * X509Certificate[], java.lang.String)
         */
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // TODO 完成X509TrustManager.checkClientTrusted方法的构建或覆盖
        }
    
        /*
         * (non-Javadoc)
         * 
         * @see
         * javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.
         * X509Certificate[], java.lang.String)
         */
        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // TODO 完成X509TrustManager.checkServerTrusted方法的构建或覆盖
        }
    
        /*
         * (non-Javadoc)
         * 
         * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
         */
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
            // TODO 完成X509TrustManager.getAcceptedIssuers方法的构建或覆盖
        }
    }

    TrustAnyHostnameVerifier.java
    package utils;
    
    import javax.net.ssl.HostnameVerifier;
    import javax.net.ssl.SSLSession;
    
    public class TrustAnyHostnameVerifier implements HostnameVerifier {
    
        /*
         * (non-Javadoc)
         * 
         * @see javax.net.ssl.HostnameVerifier#verify(java.lang.String,
         * javax.net.ssl.SSLSession)
         */
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    JerseyHttpUtils.java
    package utils;
    
    import java.net.InetAddress;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    import javax.ws.rs.core.MediaType;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.mx.kernel.StringUtil;
    import org.mx.kernel.config.ApplicationConfig;
    import org.mx.platform.base.rest.service.FastJSONProvider;
    
    import com.alibaba.fastjson.JSON;import com.sun.jersey.api.client.Client;
    import com.sun.jersey.api.client.ClientResponse;
    import com.sun.jersey.api.client.ClientResponse.Status;
    import com.sun.jersey.api.client.WebResource;
    import com.sun.jersey.api.client.config.ClientConfig;
    import com.sun.jersey.api.client.config.DefaultClientConfig;
    import com.sun.jersey.client.urlconnection.HTTPSProperties;
    
    /**
     * 基于jersey的客户端请求工具
     * 
     */
    public class JerseyHttpUtils {
    
        /** 静态变量:系统日志 */
        private static final Log logger = LogFactory.getLog(HttpUtils2.class);
    
        /** 静态变量:是否启用共享秘钥认证 */
        private static boolean SHARE_KEY_AUTH_ENABLE = false;
        /** 静态变量:客户端系统编码 */
        private static String CLIENT_SYSTEM_CODE = "";
    
        static {
            ApplicationConfig applicationConfig = ApplicationConfig.getApplicationConfig();
            if (applicationConfig != null) {
                SHARE_KEY_AUTH_ENABLE = applicationConfig.getConfigBoolean("share.key.auth.enable");
                if (applicationConfig.getConfig("client.system.code") != null) {
                    CLIENT_SYSTEM_CODE = applicationConfig.getConfig("client.system.code");
                }
            }
        }
    
        /**
         * webapi http get调用,反序列化结果
         * 
         * @param <T>
         * @param url
         * @param map
         *            参数可直接直接以?key=value的方式放在url中,也可放在map里
         * @param c
         * @return
         * @throws Exception
         */
        public static <T> T get(String url, HashMap<String, String> map, Class<T> c) throws Exception {
            try {
                Client client = getClientConfig(url);
                WebResource resource = client.resource(url);
                if (map != null && map.size() > 0) {
                    for (Map.Entry<String, String> entry : map.entrySet()) {
                        resource = resource.queryParam(entry.getKey(), entry.getValue());
                    }
                }
                ClientResponse response = null;
                if (SHARE_KEY_AUTH_ENABLE) {// 使用共享密钥认证
                    // 请求UTC时间
                    long lCurTime = System.currentTimeMillis();
                    // 获取本地IP
                    InetAddress ia = InetAddress.getLocalHost();
                    String localip = ia.getHostAddress();
                    String token = lCurTime + "," + localip + "," + CLIENT_SYSTEM_CODE;
                    String encodeToken = AES256Encryption.encrypt(token);
                    response = resource.header("tokenkey", encodeToken).get(ClientResponse.class);
                } else {// 不使用共享密钥认证
                    response = resource.get(ClientResponse.class);
                }
                if (Status.OK.equals(response.getClientResponseStatus())) {
                    String resultString = response.getEntity(String.class);
                    if (!StringUtil.isBlank(resultString)) {
                        return JSON.parseObject(resultString, c);
                    }
                }
                return null;
            } catch (Exception e) {
                if (logger.isErrorEnabled()) {
                    logger.error(e);
                }
                throw e;
            }
        }
    
        /**
         * webapi http post调用,反序列化结果
         * 
         * @throws Exception
         */
        public static <T> T post(String url, Object postObject, Class<T> c) throws Exception {
            try {
                Client client = getClientConfig(url);
                WebResource resource = client.resource(url);
                ClientResponse response = null;
                if (SHARE_KEY_AUTH_ENABLE) {// 使用共享密钥认证
                    // 请求UTC时间
                    long lCurTime = System.currentTimeMillis();
                    // 获取本地IP
                    InetAddress ia = InetAddress.getLocalHost();
                    String localip = ia.getHostAddress();
                    String token = lCurTime + "," + localip + "," + CLIENT_SYSTEM_CODE;
                    String encodeToken = AES256Encryption.encrypt(token);
                    response = resource.header("tokenkey", encodeToken).type(MediaType.APPLICATION_JSON)
                            .post(ClientResponse.class, postObject);
                } else {// 不使用共享密钥认证
                    response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, postObject);
                }
                if (Status.OK.equals(response.getClientResponseStatus())) {
                    String resultString = response.getEntity(String.class);
                    if (!StringUtil.isBlank(resultString)) {
                        return JSON.parseObject(resultString, c);
                    }
                }
                return null;
            } catch (Exception e) {
                if (logger.isErrorEnabled()) {
                    logger.error(e);
                }
                throw e;
            }
    
        }
    
        /**
         * 获取客户端配置
         * 
         * @throws Exception
         */
        public static Client getClientConfig(String url) throws Exception {
            ClientConfig config = new DefaultClientConfig(FastJSONProvider.class);
            if (url != null && url.startsWith("https")) {// https
                SSLContext ctx = SSLContext.getInstance("TLS");
                TrustManager[] tm = { new MyX509TrustManager() };
                ctx.init(null, tm, null);
                config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                        new HTTPSProperties(new TrustAnyHostnameVerifier(), ctx));
            }
            return Client.create(config);
        }
    }
    getResponseFromServer方法可以放入工具类,以下是代码片段
    public static String getResponseFromServer(final URL constructedUrl, final HttpURLConnectionFactory factory,
                final String encoding) {
    
            HttpURLConnection conn = null;
            HttpsURLConnection httpsConn = null;// https连接 20210205
            InputStreamReader in = null;
            try {
                if (constructedUrl != null && constructedUrl.toString().startsWith("https")) {//https
                    httpsConn = (HttpsURLConnection) constructedUrl.openConnection();
                    TrustManager[] tm = { new MyX509TrustManager() };
    
                    SSLContext ctx = SSLContext.getInstance("TLS");
                    ctx.init(null, tm, null);
    
                    httpsConn.setSSLSocketFactory(ctx.getSocketFactory());
                    httpsConn.setHostnameVerifier(new TrustAnyHostnameVerifier());
                    if (CommonUtils.isEmpty(encoding)) {
                        in = new InputStreamReader(httpsConn.getInputStream());
                    } else {
                        in = new InputStreamReader(httpsConn.getInputStream(), encoding);
                    }
                } else {//http
                    conn = factory.buildHttpURLConnection(constructedUrl.openConnection());
                    if (CommonUtils.isEmpty(encoding)) {
                        in = new InputStreamReader(conn.getInputStream());
                    } else {
                        in = new InputStreamReader(conn.getInputStream(), encoding);
                    }
                }
    
                final StringBuilder builder = new StringBuilder(255);
                int byteRead;
                while ((byteRead = in.read()) != -1) {
                    builder.append((char) byteRead);
                }
    
                return builder.toString();
            } catch (final RuntimeException e) {
                throw e;
            } catch (final SSLException e) {
                LOGGER.error("SSL error getting response from host: {} : Error Message: {}", constructedUrl.getHost(),
                        e.getMessage(), e);
                throw new RuntimeException(e);
            } catch (final IOException e) {
                LOGGER.error("Error getting response from host: [{}] with path: [{}] and protocol: [{}] Error Message: {}",
                        constructedUrl.getHost(), constructedUrl.getPath(), constructedUrl.getProtocol(), e.getMessage(),
                        e);
                throw new RuntimeException(e);
            } catch (NoSuchAlgorithmException e) {
                LOGGER.error("NoSuchAlgorithmException: {}", e);
                throw new RuntimeException(e);
            } catch (KeyManagementException e) {
                LOGGER.error("KeyManagementException: {}", e);
                throw new RuntimeException(e);
            } finally {
                closeQuietly(in);
                if (conn != null) {
                    conn.disconnect();
                }
                if (httpsConn != null) {
                    httpsConn.disconnect();
                }
            }
        }

    ---------------------------------------------------------------------------------------------------------------

    http、https请求 参考示例  https://www.cnblogs.com/pxblog/p/10524167.html

    http、https协议基础 https://blog.csdn.net/weixin_39942213/article/details/111264847

      

  • 相关阅读:
    redis集群规范
    mongodb的基本使用
    redis进阶
    redis基本使用
    selenium的基本使用
    C++入门
    C语言入门
    MATLAB中矩阵reshape的顺序规律
    Tensorflow:ImportError: DLL load failed: 找不到指定的模块 Failed to load the native TensorFlow runtime
    差分定位和精密定位
  • 原文地址:https://www.cnblogs.com/Alwaysbecoding/p/14375938.html
Copyright © 2011-2022 走看看