发送无证书的HTTPS请求

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 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;

/**
 * 用于进行Https请求的HttpClient
 * @ClassName: SSLClient
 * @Description: TODO
 * @author Devin <xxx>
 * @date 2017年2月7日 下午1:42:07
 *
 */
public class SSLClient extends DefaultHttpClient {
    public SSLClient() throws Exception{
        super();
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = this.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
    }
}
public static String sendSSLPostRawRequest(String url ,String params) throws Exception {
        String responseContent = null;                   //响应内容
        HttpClient httpClient = new SSLClient();
        HttpPost httpPost = new HttpPost(url);                        //创建HttpPost
        if(!StringUtils.isBlank(params))
        {
            StringEntity requestEntity = new StringEntity(params, "UTF-8");
            httpPost.setEntity(requestEntity);
        }
        HttpResponse response = httpClient.execute(httpPost); //执行POST请求
        HttpEntity entity = response.getEntity();             //获取响应实体

        if (null != entity) {
            responseContent = EntityUtils.toString(entity, "UTF-8");
            EntityUtils.consume(entity); //Consume response content
        }
        httpClient.getConnectionManager().shutdown(); //关闭连接,释放资源
        return responseContent;
    }

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页