关于httpclient 请求https (如何绕过证书验证)

标签: httpclient https 证书 | 发表时间:2012-10-15 17:56 | 作者:你爸是李刚
出处:http://www.blogjava.net
第一种方法,适用于httpclient4.X 里边有get和post两种方法供你发送请求使用。导入证书发送请求的在这里就不说了,网上到处都是


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;


import javax.net.SocketFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.scheme.HostNameResolver;
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.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;


/*
 * author:haungxuebin
 * 云南新接口
 * 
 */
public class HttpClientSendPost {
private static DefaultHttpClient client;
 /** 
     * 访问https的网站 
     * @param httpclient 
     */  
    private static void enableSSL(DefaultHttpClient httpclient){  
        //调用ssl  
         try {  
                SSLContext sslcontext = SSLContext.getInstance("TLS");  
                sslcontext.init(null, new TrustManager[] { truseAllManager }, null);  
                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();  
            }  
    }  
    /** 
     * 重写验证方法,取消检测ssl 
     */  
    private static TrustManager truseAllManager = new X509TrustManager(){  
  
        public void checkClientTrusted(  
                java.security.cert.X509Certificate[] arg0, String arg1)  
                throws CertificateException {  
            // TODO Auto-generated method stub  
              
        }  
  
        public void checkServerTrusted(  
                java.security.cert.X509Certificate[] arg0, String arg1)  
                throws CertificateException {  
            // TODO Auto-generated method stub  
              
        }  
  
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
            // TODO Auto-generated method stub  
            return null;  
        }  
          
    }; 
/**
* HTTP Client Object,used HttpClient Class before(version 3.x),but now the
* HttpClient is an interface
*/


public static String sendXMLDataByGet(String url,String xml){
   // 创建HttpClient实例     
        if (client == null) {
// Create HttpClient Object
client = new DefaultHttpClient();
enableSSL(client);
}
        StringBuilder urlString=new StringBuilder();
        urlString.append(url);
        urlString.append("?");
        System.out.println("getUTF8XMLString(xml):"+getUTF8XMLString(xml));
        try {
urlString.append(URLEncoder.encode( getUTF8XMLString(xml) , "UTF-8" ));
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
        String urlReq=urlString.toString();
        // 创建Get方法实例     
        HttpGet httpsgets = new HttpGet(urlReq);

        String strRep="";
try {
HttpResponse response = client.execute(httpsgets);    
HttpEntity entity = response.getEntity(); 

if (entity != null) { 
strRep = EntityUtils.toString(response.getEntity());
   // Do not need the rest    
   httpsgets.abort();    
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}  
        return strRep;
    } 


/**
* Send a XML-Formed string to HTTP Server by post method

* @param url
*            the request URL string
* @param xmlData
*            XML-Formed string ,will not check whether this string is
*            XML-Formed or not
* @return the HTTP response status code ,like 200 represents OK,404 not
*         found
* @throws IOException
* @throws ClientProtocolException
*/
public static String sendXMLDataByPost(String url, String xmlData)
throws ClientProtocolException, IOException {
if (client == null) {
// Create HttpClient Object
client = new DefaultHttpClient();
enableSSL(client);
}
client.getParams().setParameter("http.protocol.content-charset",
HTTP.UTF_8);
client.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
client.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
client.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET,
HTTP.UTF_8);


// System.out.println(HTTP.UTF_8);
// Send data by post method in HTTP protocol,use HttpPost instead of
// PostMethod which was occurred in former version
// System.out.println(url);
HttpPost post = new HttpPost(url);
post.getParams().setParameter("http.protocol.content-charset",
HTTP.UTF_8);
post.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
post.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
post.getParams()
.setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);


// Construct a string entity
StringEntity entity = new StringEntity(getUTF8XMLString(xmlData), "UTF-8");
entity.setContentType("text/xml;charset=UTF-8");
entity.setContentEncoding("UTF-8");
// Set XML entity
post.setEntity(entity);
// Set content type of request header
post.setHeader("Content-Type", "text/xml;charset=UTF-8");
// Execute request and get the response
HttpResponse response = client.execute(post);
HttpEntity entityRep = response.getEntity(); 
String strrep="";
        if (entityRep != null) {     
            strrep = EntityUtils.toString(response.getEntity());
            // Do not need the rest    
            post.abort();    
        }  
// Response Header - StatusLine - status code
// statusCode = response.getStatusLine().getStatusCode();
return strrep;
}
/**
* Get XML String of utf-8

* @return XML-Formed string
*/
public static String getUTF8XMLString(String xml) {
// A StringBuffer Object
StringBuffer sb = new StringBuffer();
sb.append(xml);
String xmString = "";
try {
xmString = new String(sb.toString().getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// return to String Formed
return xmString.toString();
}

}

第二种仿http的不用HttpClient 都是jdk自带的包

package org.sp.sc.util;


import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;


import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


   /**
     * 无视Https证书是否正确的Java Http Client
     * 
     * 
     * @author huangxuebin
     *
     * @create 2012.8.17
     * @version 1.0
     */
public class HttpsUtil {


    /**
     * 忽视证书HostName
     */
    private static HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
        public boolean verify(String s, SSLSession sslsession) {
            System.out.println("WARNING: Hostname is not matched for cert.");
            return true;
        }
    };


     /**
     * Ignore Certification
     */
    private static TrustManager ignoreCertificationTrustManger = new X509TrustManager() {


        private X509Certificate[] certificates;


        @Override
        public void checkClientTrusted(X509Certificate certificates[],
                String authType) throws CertificateException {
            if (this.certificates == null) {
                this.certificates = certificates;
                System.out.println("init at checkClientTrusted");
            }


        }


        @Override
        public void checkServerTrusted(X509Certificate[] ax509certificate,
                String s) throws CertificateException {
            if (this.certificates == null) {
                this.certificates = ax509certificate;
                System.out.println("init at checkServerTrusted");
            }


//            for (int c = 0; c < certificates.length; c++) {
//                X509Certificate cert = certificates[c];
//                System.out.println(" Server certificate " + (c + 1) + ":");
//                System.out.println("  Subject DN: " + cert.getSubjectDN());
//                System.out.println("  Signature Algorithm: "
//                        + cert.getSigAlgName());
//                System.out.println("  Valid from: " + cert.getNotBefore());
//                System.out.println("  Valid until: " + cert.getNotAfter());
//                System.out.println("  Issuer: " + cert.getIssuerDN());
//            }


        }


        @Override
        public X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return null;
        }


    };


    public static String getMethod(String urlString) {


        ByteArrayOutputStream buffer = new ByteArrayOutputStream(512);
        try {


            URL url = new URL(urlString);


            /*
             * use ignore host name verifier
             */
            HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();


            // Prepare SSL Context
            TrustManager[] tm = { ignoreCertificationTrustManger };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());


            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            connection.setSSLSocketFactory(ssf);
            
            InputStream reader = connection.getInputStream();
            byte[] bytes = new byte[512];
            int length = reader.read(bytes);


            do {
                buffer.write(bytes, 0, length);
                length = reader.read(bytes);
            } while (length > 0);


            // result.setResponseData(bytes);
            System.out.println(buffer.toString());
            reader.close();
            
            connection.disconnect();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
        }
        String repString= new String (buffer.toByteArray());
        return repString;
    }


//    public static void main(String[] args) {
//        String urlString = "https://218.202.0.241:8081/XMLReceiver";
//        String output = new String(HttpsUtil.getMethod(urlString));
//        System.out.println(output);
//    }
}


本文链接

相关 [httpclient https 证书] 推荐:

关于httpclient 请求https (如何绕过证书验证)

- - BlogJava_首页
第一种方法,适用于httpclient4.X 里边有get和post两种方法供你发送请求使用. 导入证书发送请求的在这里就不说了,网上到处都是.      * 访问https的网站 .         //调用ssl  .      * 重写验证方法,取消检测ssl .    // 创建HttpClient实例     .

Nginx 安装 HTTPS 证书

- - idea's blog
基本步骤可以参考 这篇文章, 但这篇文章有一个致命错误, 就是没有安装 INTERMEDIATE CA, 照样会被浏览器显示证书不可信.. 生成 server.key.orig. 生成 server.csr 和 server.key. 拿着 server.csr 去证书厂商买证书. 买完后, 厂商会给你发两个证书 server.crt 和 server.intermediate.crt.

HTTPS、SSL与数字证书介绍

- - 忘我的追寻
在互联网安全通信方式上,目前用的最多的就是https配合ssl和数字证书来保证传输和认证安全了. 本文追本溯源围绕这个模式谈一谈. HTTPS:在HTTP(超文本传输协议)基础上提出的一种安全的HTTP协议,因此可以称为安全的超文本传输协议. HTTP协议直接放置在TCP协议之上,而HTTPS提出在HTTP和TCP中间加上一层加密层.

HTTPS与SNI扩展,一个IP多个证书

- - Xiaoxia[PG]
在搭建支持HTTPS的前端代理服务器时候,通常会遇到让人头痛的证书问题. 根据HTTPS的工作原理,浏览器在访问一个HTTPS站点时,先与服务器建立SSL连接,建立连接的第一部就是请求服务器的证书. 而服务器在发送证书的时候,是不知道浏览器访问的是哪个域名的,所以不能根据不同域名发送不同的证书. 用过GoAgent的人都知道需要给浏览器导入证书才能使用HTTPS正常登录Twitter等网站.

java在访问https资源时,忽略证书信任问题

- - CSDN博客推荐文章
java程序在访问https资源时,出现报错. 这本质上,是java在访问https资源时的证书信任问题. 客户端在使用HTTPS方式与Web服务器通信时有以下几个步骤,如图所示. (1)客户使用https的URL访问Web服务器,要求与Web服务器建立SSL连接. (2)Web服务器收到客户端请求后,会将网站的证书信息(证书中包含公钥)传送一份给客户端.

salt-api https证书报错解决方法

- - 运维技术的个人空间
问题的原因是“SSL: CERTIFICATE_VERIFY_FAILED”. Python 升级到 2.7.9 之后引入了一个新特性,当使用urllib.urlopen打开一个 https 链接时,会验证一次 SSL 证书. 而当目标网站使用的是自签名的证书时就会抛出一个 urllib2.URLError: 的错误消息,详细信息可以在这里查看(https://www.python.org/dev/peps/pep-0476/).

免费SSL证书(https网站)申请 - osfipin - 博客园

- -
如何拥有一个自己的免费的SSL证书,并且能够长期拥有. 这篇文章让你找到可用的免费证书o(* ̄︶ ̄*)o. 各厂商提供的免费SSL基本是Symantec(赛门铁克),申请一年,不支持通配符,有数量限制. 免费数字证书,最多保护一个明细子域名,不支持通配符,一个阿云帐户最多签发20张免费证书. 兼容性如下操作系统版本IOS 5.0+、Android 2.3.3+、JRE 1.6.5+、WIN 7+.

HttpClient 与 Close_Wait

- - 互联网 - ITeye博客
服务器A需要通过HttpClient去连接另一个系统B提供的服务,运行一段时间后抛出以下异常:. 在服务器B上运行netstat命令,发现大量连接处于 CLOSE_WAIT 状态. 简单来说CLOSE_WAIT数目过大是由于被动关闭连接处理不当导致的. 我说一个场景,服务器A会去请求服务器B上面的apache获取文件资源,正常情况下,如果请求成功,那么在抓取完资源后服务器A会主动发出关闭连接的请求,这个时候就是主动关闭连接,连接状态我们可以看到是TIME_WAIT.

全球可信并且唯一免费的HTTPS(SSL)证书颁发机构:StartSSL

- - 行业应用 - ITeye博客
HTTPS(全称:Hypertext Transfer Protocol over Secure Socket Layer),是以安全为目标的HTTP通道,简单讲是HTTP的安全版. 即HTTP下加入SSL层,HTTPS的安全基础是SSL,因此加密的详细内容请看SSL.   它是一个URI scheme(抽象标识符体系),句法类同http:体系.

是时候支持HTTPS了:免费SSL证书letsencrypt配置教程

- - 后端技术 by Tim Yang
今天抽空将 blog 增加了 HTTPS 支持,并停止了原来的 HTTP 服务. 由于证书仅网站域名需要,因此使用了免费的 Let’s Encrypt 证书服务. 根据维基百科的说明,Let’s Encrypt 是一个于2015年三季度推出的数字证书认证机构,将通过旨在消除当前手动创建和安装证书的复杂过程的自动化流程,为安全网站提供免费的SSL/TLS证书.