zoukankan      html  css  js  c++  java
  • httpclient2

    用了大半天时间才了解如何使用httpclient来进行https访问,现记录,已备后忘。 
    
    httpclient完全支持ssl连接方式。通常,如果不需要进行客户端认证和服务器端认证的ssl连接,httpclient的处理方式是和http方式完全一样。 
    
    现在这里是讲的是需要客户端认证数字证书时的httpclient处理方式(因为需要客户端认证时,连接会被主动关闭)。 
    
    1。使用ie访问你要连结的url地址,这时你会看到弹出一个询问是否继续和服务器建立连接的对话框(安全警报)。选择“查看证书”->“详细信息”->“复制文件到”导出数字证书(例: server.cer或server.crt)。 
    
    2。使用导出的数字证书来创建你的keystore 
    
    keytool -import -alias "my server cert" -file server.cer -keystore my.truststore 
    
    keytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystore 
    
    3。在引入AuthSSLProtocolSocketFactory.java,AuthSSLX509TrustManager.java和AuthSSLInitializationError后在你的代码里按下面的例子里来进行ssl连接 
    
    Protocol authhttps = new Protocol("https",   
    
        new AuthSSLProtocolSocketFactory( 
    
            new URL("file:my.keystore"), "mypassword", 
    
            new URL("file:my.truststore"), "mypassword"), 8443); 
    
    HttpClient client = new HttpClient(); 
    
    client.getHostConfiguration().setHost("sh.12530", 8443, authhttps); 
    
    /*只能使用相对路径*/ 
    
    GetMethod httpget = new GetMethod("/"); 
    
    client.executeMethod(httpget); 
    
    附录: 
    
    AuthSSLInitializationError.java 
    
    public class AuthSSLInitializationError extends Error { 
    
        /**
         * 构招一个AuthSSLInitializationError实例
         */
        public AuthSSLInitializationError() {
            super();
        } 
    
        /**
         * 用指定信息构造一个AuthSSLInitializationError实例
         * @param message
         */
        public AuthSSLInitializationError(String message) {
            super(message);
        }
    }
    
      
    
    AuthSSLX509TrustManager.java 
    
    import java.security.cert.X509Certificate; 
    
    import com.sun.net.ssl.X509TrustManager;
    import org.apache.commons.logging.Log; 
    import org.apache.commons.logging.LogFactory; 
    
    public class AuthSSLX509TrustManager implements X509TrustManager
    {
        private X509TrustManager defaultTrustManager = null; 
    
        /** Log object for this class. */
        private static final Log LOG = LogFactory.getLog(AuthSSLX509TrustManager.class); 
    
        /**
         * Constructor for AuthSSLX509TrustManager.
         */
        public AuthSSLX509TrustManager(final X509TrustManager defaultTrustManager) {
            super();
            if (defaultTrustManager == null) {
                throw new IllegalArgumentException("Trust manager may not be null");
            }
            this.defaultTrustManager = defaultTrustManager;
        } 
    
        /**
         * @see com.sun.net.ssl.X509TrustManager#isClientTrusted(X509Certificate[])
         */
        public boolean isClientTrusted(X509Certificate[] certificates) {
            if (LOG.isInfoEnabled() && certificates != null) {
                for (int c = 0; c < certificates.length; c++) {
                    X509Certificate cert = certificates[c];
                    LOG.info(" Client certificate " + (c + 1) + ":");
                    LOG.info("  Subject DN: " + cert.getSubjectDN());
                    LOG.info("  Signature Algorithm: " + cert.getSigAlgName());
                    LOG.info("  Valid from: " + cert.getNotBefore() );
                    LOG.info("  Valid until: " + cert.getNotAfter());
                    LOG.info("  Issuer: " + cert.getIssuerDN());
                }
            }
            return this.defaultTrustManager.isClientTrusted(certificates);
        } 
    
        /**
         * @see com.sun.net.ssl.X509TrustManager#isServerTrusted(X509Certificate[])
         */
        public boolean isServerTrusted(X509Certificate[] certificates) {
            if (LOG.isInfoEnabled() && certificates != null) {
                for (int c = 0; c < certificates.length; c++) {
                    X509Certificate cert = certificates[c];
                    LOG.info(" Server certificate " + (c + 1) + ":");
                    LOG.info("  Subject DN: " + cert.getSubjectDN());
                    LOG.info("  Signature Algorithm: " + cert.getSigAlgName());
                    LOG.info("  Valid from: " + cert.getNotBefore() );
                    LOG.info("  Valid until: " + cert.getNotAfter());
                    LOG.info("  Issuer: " + cert.getIssuerDN());
                }
            }
            return this.defaultTrustManager.isServerTrusted(certificates);
        } 
    
        /**
         * @see com.sun.net.ssl.X509TrustManager#getAcceptedIssuers()
         */
        public X509Certificate[] getAcceptedIssuers() {
            return this.defaultTrustManager.getAcceptedIssuers();
        }
    } 
    
      
    
    AuthSSLProtocolSocketFactory .java 
    
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.URL;
    import java.net.UnknownHostException;
    import java.security.GeneralSecurityException;
    import java.security.KeyStore;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.UnrecoverableKeyException;
    import java.security.cert.Certificate;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import java.util.Enumeration; 
    
    import org.apache.commons.httpclient.ConnectTimeoutException;
    import org.apache.commons.httpclient.params.HttpConnectionParams;
    import org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory;
    import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
    import org.apache.commons.logging.Log; 
    import org.apache.commons.logging.LogFactory; 
    
    import com.sun.net.ssl.KeyManager;
    import com.sun.net.ssl.KeyManagerFactory;
    import com.sun.net.ssl.SSLContext;
    import com.sun.net.ssl.TrustManager;
    import com.sun.net.ssl.TrustManagerFactory;
    import com.sun.net.ssl.X509TrustManager; 
    
    public class AuthSSLProtocolSocketFactory implements SecureProtocolSocketFactory { 
    
        /** Log object for this class. */
        private static final Log LOG = LogFactory.getLog(AuthSSLProtocolSocketFactory.class); 
    
        private URL keystoreUrl = null;
        private String keystorePassword = null;
        private URL truststoreUrl = null;
        private String truststorePassword = null;
        private SSLContext sslcontext = null; 
    
        /**
         * Constructor for AuthSSLProtocolSocketFactory. Either a keystore or truststore file
         * must be given. Otherwise SSL context initialization error will result.
         * 
         * @param keystoreUrl URL of the keystore file. May be <tt>null</tt> if HTTPS client
         *        authentication is not to be used.
         * @param keystorePassword Password to unlock the keystore. IMPORTANT: this implementation
         *        assumes that the same password is used to protect the key and the keystore itself.
         * @param truststoreUrl URL of the truststore file. May be <tt>null</tt> if HTTPS server
         *        authentication is not to be used.
         * @param truststorePassword Password to unlock the truststore.
         */
        public AuthSSLProtocolSocketFactory(
            final URL keystoreUrl, final String keystorePassword, 
            final URL truststoreUrl, final String truststorePassword)
        {
            super();
            this.keystoreUrl = keystoreUrl;
            this.keystorePassword = keystorePassword;
            this.truststoreUrl = truststoreUrl;
            this.truststorePassword = truststorePassword;
        } 
    
        private static KeyStore createKeyStore(final URL url, final String password) 
            throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException
        {
            if (url == null) {
                throw new IllegalArgumentException("Keystore url may not be null");
            }
            LOG.debug("Initializing key store");
            KeyStore keystore  = KeyStore.getInstance("jks");
            keystore.load(url.openStream(), password != null ? password.toCharArray(): null);
            return keystore;
        }
        
        private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password)
            throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException 
        {
            if (keystore == null) {
                throw new IllegalArgumentException("Keystore may not be null");
            }
            LOG.debug("Initializing key manager");
            KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
                KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keystore, password != null ? password.toCharArray(): null);
            return kmfactory.getKeyManagers(); 
        } 
    
        private static TrustManager[] createTrustManagers(final KeyStore keystore)
            throws KeyStoreException, NoSuchAlgorithmException
        { 
            if (keystore == null) {
                throw new IllegalArgumentException("Keystore may not be null");
            }
            LOG.debug("Initializing trust manager");
            TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
                TrustManagerFactory.getDefaultAlgorithm());
            tmfactory.init(keystore);
            TrustManager[] trustmanagers = tmfactory.getTrustManagers();
            for (int i = 0; i < trustmanagers.length; i++) {
                if (trustmanagers[i] instanceof X509TrustManager) {
                    trustmanagers[i] = new AuthSSLX509TrustManager(
                        (X509TrustManager)trustmanagers[i]); 
                }
            }
            return trustmanagers; 
        } 
    
        private SSLContext createSSLContext() {
            try {
                KeyManager[] keymanagers = null;
                TrustManager[] trustmanagers = null;
                if (this.keystoreUrl != null) {
                    KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
                    if (LOG.isDebugEnabled()) {
                        Enumeration aliases = keystore.aliases();
                        while (aliases.hasMoreElements()) {
                            String alias = (String)aliases.nextElement();                        
                            Certificate[] certs = keystore.getCertificateChain(alias);
                            if (certs != null) {
                                LOG.debug("Certificate chain '" + alias + "':");
                                for (int c = 0; c < certs.length; c++) {
                                    if (certs[c] instanceof X509Certificate) {
                                        X509Certificate cert = (X509Certificate)certs[c];
                                        LOG.debug(" Certificate " + (c + 1) + ":");
                                        LOG.debug("  Subject DN: " + cert.getSubjectDN());
                                        LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                        LOG.debug("  Valid from: " + cert.getNotBefore() );
                                        LOG.debug("  Valid until: " + cert.getNotAfter());
                                        LOG.debug("  Issuer: " + cert.getIssuerDN());
                                    }
                                }
                            }
                        }
                    }
                    keymanagers = createKeyManagers(keystore, this.keystorePassword);
                }
                if (this.truststoreUrl != null) {
                    KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
                    if (LOG.isDebugEnabled()) {
                        Enumeration aliases = keystore.aliases();
                        while (aliases.hasMoreElements()) {
                            String alias = (String)aliases.nextElement();
                            LOG.debug("Trusted certificate '" + alias + "':");
                            Certificate trustedcert = keystore.getCertificate(alias);
                            if (trustedcert != null && trustedcert instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate)trustedcert;
                                LOG.debug("  Subject DN: " + cert.getSubjectDN());
                                LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                LOG.debug("  Valid from: " + cert.getNotBefore() );
                                LOG.debug("  Valid until: " + cert.getNotAfter());
                                LOG.debug("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                    trustmanagers = createTrustManagers(keystore);
                }
                SSLContext sslcontext = SSLContext.getInstance("SSL");
                sslcontext.init(keymanagers, trustmanagers, null);
                return sslcontext;
            } catch (NoSuchAlgorithmException e) {
                LOG.error(e.getMessage(), e);
                throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
            } catch (KeyStoreException e) {
                LOG.error(e.getMessage(), e);
                throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
            } catch (GeneralSecurityException e) {
                LOG.error(e.getMessage(), e);
                throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
            } catch (IOException e) {
                LOG.error(e.getMessage(), e);
                throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
            }
        } 
    
        private SSLContext getSSLContext() {
            if (this.sslcontext == null) {
                this.sslcontext = createSSLContext();
            }
            return this.sslcontext;
        } 
    
        /**
         * Attempts to get a new socket connection to the given host within the given time limit.
         * <p>
         * To circumvent the limitations of older JREs that do not support connect timeout a 
         * controller thread is executed. The controller thread attempts to create a new socket 
         * within the given limit of time. If socket constructor does not return until the 
         * timeout expires, the controller terminates and throws an {@link ConnectTimeoutException}
         * </p>
         *  
         * @param host the host name/IP
         * @param port the port on the host
         * @param clientHost the local host name/IP to bind the socket to
         * @param clientPort the port on the local machine
         * @param params {@link HttpConnectionParams Http connection parameters}
         * 
         * @return Socket a new socket
         * 
         * @throws IOException if an I/O error occurs while creating the socket
         * @throws UnknownHostException if the IP address of the host cannot be
         * determined
         */
        public Socket createSocket(
            final String host,
            final int port,
            final InetAddress localAddress,
            final int localPort,
            final HttpConnectionParams params
        ) throws IOException, UnknownHostException, ConnectTimeoutException {
            if (params == null) {
                throw new IllegalArgumentException("Parameters may not be null");
            }
            int timeout = params.getConnectionTimeout();
            if (timeout == 0) {
                return createSocket(host, port, localAddress, localPort);
            } else {
                // To be eventually deprecated when migrated to Java 1.4 or above
                return ControllerThreadSocketFactory.createSocket(
                        this, host, port, localAddress, localPort, timeout);
            }
        } 
    
        /**
         * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int)
         */
        public Socket createSocket(
            String host,
            int port,
            InetAddress clientHost,
            int clientPort)
            throws IOException, UnknownHostException
       {
           return getSSLContext().getSocketFactory().createSocket(
                host,
                port,
                clientHost,
                clientPort
            );
        } 
    
        /**
         * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int)
         */
        public Socket createSocket(String host, int port)
            throws IOException, UnknownHostException
        {
            return getSSLContext().getSocketFactory().createSocket(
                host,
                port
            );
        } 
    
        /**
         * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)
         */
        public Socket createSocket(
            Socket socket,
            String host,
            int port,
            boolean autoClose)
            throws IOException, UnknownHostException
        {
            return getSSLContext().getSocketFactory().createSocket(
                socket,
                host,
                port,
                autoClose
            );
        }
    }

    HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。本文首先介绍 HTTPClient,然后根据作者实际工作经验给出了一些常见问题的解决方法。

    package com.jadyer.util;   
      
    import java.io.IOException;   
    import java.io.UnsupportedEncodingException;   
    import java.security.KeyManagementException;   
    import java.security.NoSuchAlgorithmException;   
    import java.security.cert.CertificateException;   
    import java.security.cert.X509Certificate;   
    import java.util.ArrayList;   
    import java.util.HashMap;   
    import java.util.List;   
    import java.util.Map;   
      
    import javax.net.ssl.SSLContext;   
    import javax.net.ssl.TrustManager;   
    import javax.net.ssl.X509TrustManager;   
      
    import org.apache.http.HttpEntity;   
    import org.apache.http.HttpResponse;   
    import org.apache.http.NameValuePair;   
    import org.apache.http.ParseException;   
    import org.apache.http.client.ClientProtocolException;   
    import org.apache.http.client.HttpClient;   
    import org.apache.http.client.entity.UrlEncodedFormEntity;   
    import org.apache.http.client.methods.HttpPost;   
    import org.apache.http.conn.scheme.Scheme;   
    import org.apache.http.conn.ssl.SSLSocketFactory;   
    import org.apache.http.impl.client.DefaultHttpClient;   
    import org.apache.http.message.BasicNameValuePair;   
    import org.apache.http.util.EntityUtils;   
      
    /**  
     * @see =====================================================================================================  
     * @see 在开发HTTPS应用时,时常会遇到两种情况  
     * @see 1、要么测试服务器没有有效的SSL证书,客户端连接时就会抛异常  
     * @see    javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated  
     * @see 2、要么测试服务器有SSL证书,但可能由于各种不知名的原因,它还是会抛一堆烂码七糟的异常  
     * @see =====================================================================================================  
     * @see 由于我们这里使用的是HttpComponents-Client-4.1.2创建的连接,所以,我们就要告诉它使用一个不同的TrustManager  
     * @see TrustManager是一个用于检查给定的证书是否有效的类  
     * @see SSL使用的模式是X.509....对于该模式,Java有一个特定的TrustManager,称为X509TrustManager  
     * @see 所以我们自己创建一个X509TrustManager实例  
     * @see 而在X509TrustManager实例中,若证书无效,那么TrustManager在它的checkXXX()方法中将抛出CertificateException  
     * @see 既然我们要接受所有的证书,那么X509TrustManager里面的方法体中不抛出异常就行了  
     * @see 然后创建一个SSLContext并使用X509TrustManager实例来初始化之  
     * @see 接着通过SSLContext创建SSLSocketFactory,最后将SSLSocketFactory注册给HttpClient就可以了  
     * @see =====================================================================================================  
     * @create Jul 30, 2012 1:11:52 PM  
     * @author 玄玉(http://blog.csdn/net/jadyer)  
     */  
    public class HttpClientUtil {   
        public static void main(String[] args)throws Exception{   
            Map<String, String> params = new HashMap<String, String>();   
            params.put("TransName", "IQSR");   
            params.put("Plain", "transId=IQSR~|~originalorderId=2012~|~originalTransAmt= ~|~merURL= ");   
            params.put("Signature", "9b759887e6ca9d4c24509d22ee4d22494d0dd2dfbdbeaab3545c1acee62eec7");   
            sendSSLPostRequest("https://www.cebbank.com/per/QueryMerchantEpay.do", params);   
        }   
           
        /**  
         * 向HTTPS地址发送POST请求  
         * @see 该方法会自动关闭连接,释放资源  
         * @param reqURL 请求地址  
         * @param params 请求参数  
         * @return 响应内容  
         */  
        public static String sendSSLPostRequest(String reqURL, Map<String, String> params){   
            long responseLength = 0;                         //响应长度   
            String responseContent = "";                     //响应内容   
            HttpClient httpClient = new DefaultHttpClient(); //创建默认的httpClient实例   
            X509TrustManager xtm = new X509TrustManager(){   //创建TrustManager   
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}   
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}   
                public X509Certificate[] getAcceptedIssuers() { return null; }   
            };   
            try {   
                //TLS1.0与SSL3.0基本上没有太大的差别,可粗略理解为TLS是SSL的继承者,但它们使用的是相同的SSLContext   
                SSLContext ctx = SSLContext.getInstance("TLS");   
                   
                //使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用   
                ctx.init(null, new TrustManager[]{xtm}, null);   
                   
                //创建SSLSocketFactory   
                SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);   
                   
                //通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上   
                httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));   
                   
                HttpPost httpPost = new HttpPost(reqURL);                        //创建HttpPost   
                List<NameValuePair> formParams = new ArrayList<NameValuePair>(); //构建POST请求的表单参数   
                for(Map.Entry<String,String> entry : params.entrySet()){   
                    formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));   
                }   
                httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));   
                   
                HttpResponse response = httpClient.execute(httpPost); //执行POST请求   
                HttpEntity entity = response.getEntity();             //获取响应实体   
                   
                if (null != entity) {   
                    responseLength = entity.getContentLength();   
                    responseContent = EntityUtils.toString(entity, "UTF-8");   
                    EntityUtils.consume(entity); //Consume response content   
                }   
                System.out.println("请求地址: " + httpPost.getURI());   
                System.out.println("响应状态: " + response.getStatusLine());   
                System.out.println("响应长度: " + responseLength);   
                System.out.println("响应内容: " + responseContent);   
            } catch (KeyManagementException e) {   
                e.printStackTrace();   
            } catch (NoSuchAlgorithmException e) {   
                e.printStackTrace();   
            } catch (UnsupportedEncodingException e) {   
                e.printStackTrace();   
            } catch (ClientProtocolException e) {   
                e.printStackTrace();   
            } catch (ParseException e) {   
                e.printStackTrace();   
            } catch (IOException e) {   
                e.printStackTrace();   
            } finally {   
                httpClient.getConnectionManager().shutdown(); //关闭连接,释放资源   
            }   
            return responseContent;   
        }   
    }
    import java.io.BufferedReader; 
    import java.io.FileInputStream; 
    import java.io.InputStreamReader; 
    import java.net.URLDecoder; 
    import java.security.KeyStore; 
    import java.util.ArrayList; 
    import java.util.HashMap; 
    import java.util.Iterator; 
    import java.util.List; 
    import java.util.Map; 
     
    import javax.net.ssl.KeyManagerFactory; 
     
    import javax.net.ssl.SSLContext; 
    import javax.net.ssl.TrustManager; 
    import javax.net.ssl.TrustManagerFactory; 
     
    import org.apache.http.HttpResponse; 
    import org.apache.http.NameValuePair; 
    import org.apache.http.client.HttpClient; 
    import org.apache.http.client.entity.UrlEncodedFormEntity; 
    import org.apache.http.client.methods.HttpPost; 
    import org.apache.http.conn.scheme.Scheme; 
    import org.apache.http.conn.ssl.SSLSocketFactory; 
    import org.apache.http.impl.client.DefaultHttpClient; 
    import org.apache.http.message.BasicNameValuePair; 
     
    public String connect(String url1, String xml) throws Exception { 
            BufferedReader in = null; 
            String keyStore = "c:\\a.pfx"; //证书的路径,pfx格式
            String trustStore = "c:\\b.jks";//密钥库文件,jks格式 
            String keyPass ="111111"; //pfx文件的密码
            String trustPass = "22222"; //jks文件的密码
     
            SSLContext sslContext = null; 
            try { 
     
                KeyStore ks = KeyStore.getInstance("pkcs12"); 
                // 加载pfx文件            
                 ks.load(new FileInputStream(keyStore), keyPass.toCharArray()); 
                KeyManagerFactory kmf = KeyManagerFactory.getInstance("sunx509"); 
                kmf.init(ks, keyPass.toCharArray()); 
     
                KeyStore ts = KeyStore.getInstance("jks"); 
              //加载jks文件            
                 ts.load(new FileInputStream(trustStore), trustPass.toCharArray()); 
                TrustManager[] tm; 
                TrustManagerFactory tmf = TrustManagerFactory.getInstance("sunx509"); 
                tmf.init(ts); 
                tm = tmf.getTrustManagers(); 
     
                sslContext = SSLContext.getInstance("SSL"); 
    //初始化
                sslContext.init(kmf.getKeyManagers(), tm, null); 
     
            } catch (Exception e) { 
                e.printStackTrace(); 
            } 
     
            String result = null; 
            try { 
     
                HttpClient httpclient = new DefaultHttpClient(); 
                 //下面是重点
                SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext); 
                Scheme sch = new Scheme("https", 800, socketFactory); 
                httpclient.getConnectionManager().getSchemeRegistry().register(sch); 
                HttpPost httpPost = null; 
     
                httpPost = new HttpPost(queryUrl); 
     
                // 创建名/值组列表 
                List<NameValuePair> parameters = new ArrayList<NameValuePair>(); 
                parameters.add(new BasicNameValuePair("Name", "zhangsan")); 
                parameters.add(new BasicNameValuePair("passWord", "123456")); 
               
                // 创建UrlEncodedFormEntity对象 
                UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(parameters); 
                LOGGER.info("formEntity={}", formEntiry); 
                httpPost.setEntity(formEntiry); 
                HttpResponse httpResponse = httpclient.execute(httpPost); 
                in = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); 
                StringBuffer sb = new StringBuffer(""); 
                String line = ""; 
                String NL = System.getProperty("line.separator"); 
                while ((line = in.readLine()) != null) { 
                    sb.append(line + NL); 
                } 
                in.close(); 
                result = sb.toString(); 
     
                result = URLDecoder.decode(result.toString(), "GBK"); 
                LOGGER.info("result={}", result); 
                return result; 
            } finally { 
                if (in != null) { 
                    try { 
                        in.close(); 
                    } catch (Exception e) { 
                        e.printStackTrace(); 
                    } 
                } 
            } 
     
        } 
    A tutorial on how to configure https in HttpClient
    Apache Commons HttpClient is a very useful API when you need your java application to communicate with websites that use HTTP protocol or RESTful web services.In cases you need to use HttpClient with HTTPS protocol there is some configuration that must be done before you can make POST or GET requests.
    package com.javaonly.test;
    
    import java.io.IOException;
    
    import java.security.NoSuchAlgorithmException;
    
    import javax.net.ssl.SSLContext;
    
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.ResponseHandler;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.conn.ClientConnectionManager;
    
    import org.apache.http.conn.scheme.Scheme;
    import org.apache.http.conn.scheme.SchemeRegistry;
    import org.apache.http.conn.scheme.SchemeSocketFactory;
    import org.apache.http.conn.ssl.SSLSocketFactory;
    import org.apache.http.impl.client.BasicResponseHandler;
    import org.apache.http.impl.client.ClientParamsStack;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.params.DefaultedHttpParams;
    import org.apache.http.params.HttpParams;
    
    public class HttpClientTest {
    
        public static void main(String args[]) {
    
            try {
    
                HttpClient httpclient = new DefaultHttpClient();
                            //Secure Protocol implementation.
                SSLContext ctx = SSLContext.getInstance("SSL");
                            //Implementation of a trust manager for X509 certificates
                X509TrustManager tm = new X509TrustManager() {
    
                    public void checkClientTrusted(X509Certificate[] xcs,
                            String string) throws CertificateException {
    
                    }
    
                    public void checkServerTrusted(X509Certificate[] xcs,
                            String string) throws CertificateException {
                    }
    
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                };
                ctx.init(null, new TrustManager[] { tm }, null);
                SSLSocketFactory ssf = new SSLSocketFactory(ctx);
    
                ClientConnectionManager ccm = httpclient.getConnectionManager();
                            //register https protocol in httpclient's scheme registry
                SchemeRegistry sr = ccm.getSchemeRegistry();
                sr.register(new Scheme("https", 443, ssf));
    
                HttpGet httpget = new HttpGet("");
                HttpParams params = httpclient.getParams();
    
                params.setParameter("param1", "paramValue1");
    
                httpget.setParams(params);
                System.out.println("REQUEST:" + httpget.getURI());
                ResponseHandler responseHandler = new BasicResponseHandler();
                String responseBody;
    
                responseBody = httpclient.execute(httpget, responseHandler);
    
                System.out.println(responseBody);
    
                // Create a response handler
    
            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception ex) {
                ex.printStackTrace();
    
            }
        }
    }
    
     As you can see in the above code snippet we first got an SSLContext instance for SSL protocol.This is actually an implementation of SSL protocol that will be used later for the creation of secure sockets through SSLSocketFactory.In order to initialize SSLContext we will need a trust manager that will handle certificates and for this example we used X509TrustManager that will manage X509 certifications.The final step before we can use HttpClient with https is to register https protocol in httpClient's schemeRegistry
  • 相关阅读:
    自动化测试-appium常用元素
    自动化测试-微信小程序
    自动化测试-环境搭建appium for windows
    安全测试-docker搭建sonar完成代码质量检测
    工具安装-pycharm使用已配置的虚拟环境
    安全测试-sonarscanner扫描代码
    工具安装-java集成到maven
    iOS 提升代码的安全性,可以做哪些措施???
    iOS 绘制一个表盘时钟,秒针效果可以“扫秒/游走”
    iOS 关于BTC 一些知识点
  • 原文地址:https://www.cnblogs.com/dollarzhaole/p/2852082.html
Copyright © 2011-2022 走看看