欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

httpcomponents+https支持

程序员文章站 2022-04-01 22:05:53
...
用于发送https请求,不需要对服务器的CA认证
http://hc.apache.org/httpcomponents-client/tutorial/html/connmgmt.html#d4e470

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;//
import java.security.cert.CertificateException;//
import java.security.cert.X509Certificate;//

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;//注意导入
import javax.servlet.http.HttpServletRequest;//注意导入
import javax.servlet.http.HttpServletResponse;//注意导入

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
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.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpClintUrlTool {

private HttpServletRequest request;
private HttpServletResponse response;
private String urlconn;
private String params;

    public  void send(String address) throws Exception {
        DefaultHttpClient httpclient0 = new DefaultHttpClient();
        DefaultHttpClient httpclient=useTrustingTrustManager(httpclient0);//关键方法
        HttpGet httpget = new HttpGet(this.urlconn);
        // Execute HTTP request
//        System.out.println("executing request " + httpget.getURI());
        HttpResponse response = httpclient.execute(httpget);
        System.out.println(response.getStatusLine());
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
            try {
                System.out.println(reader.readLine());
            } catch (IOException ex) {
                throw ex;
            } catch (RuntimeException ex) {
                httpget.abort();
                throw ex;
               
            } finally {
                reader.close();
            }
        }
        httpclient.getConnectionManager().shutdown();       
    }
   
    /**
     *
     * @param httpClient
     * @return
     */
    public static DefaultHttpClient useTrustingTrustManager(DefaultHttpClient httpClient)
{
       try
       {
// First create a trust manager that won't care.
X509TrustManager trustManager = new X509TrustManager()
{
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
// Don't do anything.
}

public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
// Don't do anything.
}

public X509Certificate[] getAcceptedIssuers()
{
// Don't do anything.
return null;
}
};

// Now put the trust manager into an SSLContext.
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] { trustManager }, null);

// Use the above SSLContext to create your socket factory
// (I found trying to extend the factory a bit difficult due to a
// call to createSocket with no arguments, a method which doesn't
// exist anywhere I can find, but hey-ho).
SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

// If you want a thread safe client, use the ThreadSafeConManager, but
// otherwise just grab the one from the current client, and get hold of its
// schema registry. THIS IS THE KEY THING.
ClientConnectionManager ccm = httpClient.getConnectionManager();
SchemeRegistry schemeRegistry = ccm.getSchemeRegistry();

// Register our new socket factory with the typical SSL port and the
// correct protocol name.
schemeRegistry.register(new Scheme("https", sf, 443));

// Finally, apply the ClientConnectionManager to the Http Client
// or, as in this example, create a new one.
return new DefaultHttpClient(ccm, httpClient.getParams());
}
catch(Throwable t)
{
// AND NEVER EVER EVER DO THIS, IT IS LAZY AND ALMOST ALWAYS WRONG!
t.printStackTrace();
return null;
}
}
   

}