httpclient无证书访问

HTTPS请求处理与证书忽略
本文介绍了一种使用Java实现的HTTPS请求处理方法,并详细展示了如何通过编程方式忽略SSL证书验证,适用于测试环境或特殊情况下的需求。
import java.io.UnsupportedEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;


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.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;


public class HttpPostInvoke {
    
    private static HttpPostInvoke invoke;
    
    private HttpPostInvoke(){
        
    };
    
    public static HttpPostInvoke getInstance(){
        if(invoke == null){
            invoke = new HttpPostInvoke();
        }
        return invoke;
    }


    public static String post(String url, Map<String, Object> params) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        String body = null;


        HttpPost post = postForm(url, params);


        body = invoke(httpclient, post);


        httpclient.getConnectionManager().shutdown();


        return body;
    }


    public static String get(String url) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        String body = null;


        HttpGet get = new HttpGet(url);
        body = invoke(httpclient, get);


        httpclient.getConnectionManager().shutdown();


        return body;
    }


    private static String invoke(DefaultHttpClient httpclient,
            HttpUriRequest httpost) {


        HttpResponse response = sendRequest(httpclient, httpost);
        String body = paseResponse(response);


        return body;
    }


    private static String paseResponse(HttpResponse response) {
        HttpEntity entity = response.getEntity();


        String charset = EntityUtils.getContentCharSet(entity);


        String body = null;
        try {
            body = EntityUtils.toString(entity);
        } catch (Exception e) {


        }
        return body;
    }


    private static HttpResponse sendRequest(DefaultHttpClient httpclient,
            HttpUriRequest httpost) {
        HttpResponse response = null;


        try {
            response = httpclient.execute(httpost);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }


    private static HttpPost postForm(String url, Map<String, Object> params) {
        HttpPost httpost = new HttpPost(url);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        Set<String> keySet = params.keySet();
        for (String key : keySet) {
            nvps.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
        }


        try {
            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


        return httpost;
    }
    
    
    /**
     * @Description:忽略证书 --- 这段最重要
     * @Title: enableSSL 
     * @param:@param httpclient
     * @return:void
     * @author lh
     * @date 2017-1-10 下午4:16:53
     * @throws
     */
    public static void enableSSL(DefaultHttpClient httpclient) {  
        try {


            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[]{
                new X509TrustManager(){
                    
                    @Override
                    public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
                        throws CertificateException {
                        
                    }
                    
                    @Override
                    public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
                        throws CertificateException {
                        
                    }
                    
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }}
            }, new java.security.SecureRandom()); 
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Scheme https = new Scheme("https", sf, 443);
            httpclient.getConnectionManager().getSchemeRegistry().register(https);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }  


    public static String post(String url, String params){  
        DefaultHttpClient httpclient = new DefaultHttpClient();
        enableSSL(httpclient);//忽略证书
        httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
        HttpPost post = new HttpPost(url);  
        StringEntity entity = new StringEntity(params, "UTF-8");
        entity.setContentEncoding("UTF-8");    
        entity.setContentType("application/json");    
        post.setEntity(entity);  
        String body = invoke(httpclient, post);
        httpclient.getConnectionManager().shutdown();
        return body;
    }  
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值