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

时间:2025-02-12 20:40:03
第一种方法,适用于 里边有get和post两种方法供你发送请求使用。导入证书发送请求的在这里就不说了,网上到处都是


import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import .X509Certificate;


import ;
import ;
import ;
import ;
import ;
import ;
import .X509TrustManager;


import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;


/*
 * author:haungxuebin
 * 云南新接口
 * 
 */
public class HttpClientSendPost {
private static DefaultHttpClient client;
 /** 
     * 访问https的网站 
     * @param httpclient 
     */  
    private static void enableSSL(DefaultHttpClient httpclient){  
        //调用ssl  
         try {  
                SSLContext sslcontext = ("TLS");  
                (null, new TrustManager[] { truseAllManager }, null);  
                SSLSocketFactory sf = new SSLSocketFactory(sslcontext);  
                (SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
                Scheme https = new Scheme("https", sf, 443);  
                ().getSchemeRegistry().register(https);  
            } catch (Exception e) {  
                ();  
            }  
    }  
    /** 
     * 重写验证方法,取消检测ssl 
     */  
    private static TrustManager truseAllManager = new X509TrustManager(){  
  
        public void checkClientTrusted(  
                .X509Certificate[] arg0, String arg1)  
                throws CertificateException {  
            // TODO Auto-generated method stub  
              
        }  
  
        public void checkServerTrusted(  
                .X509Certificate[] arg0, String arg1)  
                throws CertificateException {  
            // TODO Auto-generated method stub  
              
        }  
  
        public .X509Certificate[] getAcceptedIssuers() {  
            // TODO Auto-generated method stub  
            return null;  
        }  
          
    }; 
/**
* HTTP Client Object,used HttpClient Class before(version ),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();
        (url);
        ("?");
        ("getUTF8XMLString(xml):"+getUTF8XMLString(xml));
        try {
(( getUTF8XMLString(xml) , "UTF-8" ));
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
();
}
        String urlReq=();
        // 创建Get方法实例     
        HttpGet httpsgets = new HttpGet(urlReq);

        String strRep="";
try {
HttpResponse response = (httpsgets);    
HttpEntity entity = (); 

if (entity != null) { 
strRep = (());
   // Do not need the rest    
   ();    
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
();
} catch (IOException e) {
// TODO Auto-generated catch block
();
}  
        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);
}
().setParameter("-charset",
HTTP.UTF_8);
().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET,
HTTP.UTF_8);


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


// Construct a string entity
StringEntity entity = new StringEntity(getUTF8XMLString(xmlData), "UTF-8");
("text/xml;charset=UTF-8");
("UTF-8");
// Set XML entity
(entity);
// Set content type of request header
("Content-Type", "text/xml;charset=UTF-8");
// Execute request and get the response
HttpResponse response = (post);
HttpEntity entityRep = (); 
String strrep="";
        if (entityRep != null) {     
            strrep = (());
            // Do not need the rest    
            ();    
        }  
// Response Header - StatusLine - status code
// statusCode = ().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();
(xml);
String xmString = "";
try {
xmString = new String(().getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
();
}
// return to String Formed
return ();
}

}

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

package ;


import ;
import ;
import ;
import ;
import .X509Certificate;


import ;
import ;
import ;
import ;
import ;
import ;
import .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) {
            ("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 ( == null) {
                = certificates;
                ("init at checkClientTrusted");
            }


        }


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


//            for (int c = 0; c < ; c++) {
//                X509Certificate cert = certificates[c];
//                (" Server certificate " + (c + 1) + ":");
//                ("  Subject DN: " + ());
//                ("  Signature Algorithm: "
//                        + ());
//                ("  Valid from: " + ());
//                ("  Valid until: " + ());
//                ("  Issuer: " + ());
//            }


        }


        @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
             */
            (ignoreHostnameVerifier);
            HttpsURLConnection connection = (HttpsURLConnection) ();


            // Prepare SSL Context
            TrustManager[] tm = { ignoreCertificationTrustManger };
            SSLContext sslContext = ("SSL", "SunJSSE");
            (null, tm, new ());


            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = ();
            (ssf);
            
            InputStream reader = ();
            byte[] bytes = new byte[512];
            int length = (bytes);


            do {
                (bytes, 0, length);
                length = (bytes);
            } while (length > 0);


            // (bytes);
            (());
            ();
            
            ();
        } catch (Exception ex) {
            ();
        } finally {
        }
        String repString= new String (());
        return repString;
    }


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