`
dailiang0515
  • 浏览: 33324 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
文章分类
社区版块
存档分类
最新评论

绕过https安全验证(纯搬运)

阅读更多

纯搬运:http://blog.csdn.net/sunny243788557/article/details/7903690

 

第一种方法,适用于httpclient4.0.3 里边有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);
//    }
}

 

分享到:
评论

相关推荐

    智能搬运车(体现电子与程序的结合 )

    - **障碍物检测与绕行**:通过超声波传感器或激光雷达等传感器检测前方障碍物,并调整路径绕过障碍物。 - **高级路径规划**:优化路径规划算法,提高搬运效率,确保在更短时间内完成搬运任务。 - **精确计时**:...

    红米主题商店收费主题任意下载补丁(搬运工)

    补丁可能包含对系统APK的修改,比如主题商店的APK,以移除或绕过支付验证。 然而,这种做法存在一定的风险,比如可能破坏系统的稳定性,导致安全漏洞,甚至让设备容易受到恶意软件的攻击。此外,随着系统更新,这些...

    高压电动机检修标准.pdf

    在定子检修中,工作人员需彻底清理定子内部,检查铁芯、端部绕组和通风回路,确保不存在锈蚀、松动或过热等现象。而对转子的检修,则是清理通风槽、检查铁芯、平衡块、鼠笼条和风扇等部件的完整性和状况。只有当所有...

    htc刷机术语

    3. 金卡(Gold Card):这是一种特殊的存储卡,通过在其头部写入特定字串来绕过地区验证,允许用户刷入不受官方支持的 ROM。金卡制作完成后,除了其特殊功能外,使用上与普通存储卡无异。 4. zip 包:通常情况下,...

    LDY型冶金电动单梁使说明书.docx

    在规定载荷下进行试验,验证起重机的实际工作能力和稳定性。 #### 九、起重机的检修与维护 **日检:** 每日检查起重机的外观状况,检查电气系统、制动系统是否正常,及时发现并解决潜在问题。 **月检:** 每月对...

    pixel 破电信.zip

    这个压缩包文件可能包含了一套修改过的系统固件或者基带文件,允许用户绕过原厂限制,实现对电信网络的支持。 【描述】中提到的"直接刷入"意味着用户需要通过刷机的方式来应用这个更新。刷机是一种高级操作,通常...

    2021年FMEA经典案例.docx

    - 原材料包装不完善可能导致运输过程中的损坏,如碰撞和储存时间过长影响材料性能。解决方案包括制定严格的供应商包装标准,执行仓库人员的外观检查,以及采用固定容器运输以减少破损。 - 原材料表面生锈、无毛刺...

    大型机电设备安装试运行故障的分析.docx

    调试是机电设备安装后的必要步骤,无论新设备还是经过拆卸、搬运、再次安装的旧设备,都需要进行调试以恢复或优化其功能。调试前,需对设备的完整性、合理性、安全性进行全面检查,以保证调试工作的顺利进行。调试时...

    移动机器人智能避障算法仿真研究 (2010年)

    为了确保机器人能够安全地从起点移动到终点而不发生碰撞,需要设计一种策略使其能够绕过这些障碍物。本研究提出的方法是将障碍物边缘的预先检测位置设定为一系列子目标,机器人通过依次达到这些子目标来完成避障任务...

    自动化专业英语词汇表

    - **定义**: 验收测试是在软件或硬件产品完成开发后的最后一个阶段进行的一系列测试活动,旨在验证产品是否满足用户需求。 - **应用场景**: 在自动化系统集成完成后,进行验收测试确保整个系统的功能性和可靠性...

Global site tag (gtag.js) - Google Analytics