Java POST请求 适配HTTPS之忽略证书

2016-1-1 Linyuting.cn 个人日志

    在搞个安卓APP的时候,遇到一个https请求问题,因为证书原因导致请求总是失败,找到一个非常简便的解决方法。以下贴出我的POST请求类。由于主线程中访问网络可能导致阻塞,该post实现是以独立线程的形式进行的。下面是类和调用方法


请求调用类

public class HttpRequest {
    public static void sendPost(String url, String params, HttpRequestCallback hrc) {
    	HttpPostThread hpt = new HttpPostThread(url, params, hrc);
    	hpt.start();
    }    
}


POST线程类

class HttpPostThread extends Thread {  
    
	String url = "";
	String params = "";
	HttpRequestCallback hrc = null;
	
    public HttpPostThread(String url, String params, HttpRequestCallback hrc){  
    	this.url = url;
    	this.params = params;
    	this.hrc = hrc;
    }  
    
    public void run() {
    	PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
        	
        	TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){  
                public X509Certificate[] getAcceptedIssuers(){return null;}  
                public void checkClientTrusted(X509Certificate[] certs, String authType){}  
                public void checkServerTrusted(X509Certificate[] certs, String authType){}  
            }};  
        	
        	HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
            SSLContext sc = SSLContext.getInstance("TLS");  
            sc.init(null, trustAllCerts, new SecureRandom());  
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        	
            URL realUrl = new URL(this.url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            out = new PrintWriter(conn.getOutputStream());
            out.print(this.params);
            out.flush();
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("POST Error!"+e);
            e.printStackTrace();
        }
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        hrc.Callback(result);
    }  
    
}

class NullHostNameVerifier implements HostnameVerifier {  
  
    @Override     
    public boolean verify(String hostname, SSLSession session) {  
        Log.i("RestUtilImpl", "Approving certificate for " + hostname);  
        return true;  
    }  
  
}  


//  请求回调接
package com.example.hellow;

public interface HttpRequestCallback {
 
 public void Callback(String requestContent);

}
 
//回调辅助类
class QhHttpRequestCallback implements HttpRequestCallback{
 
 public Context context = null;
 
 public QhHttpRequestCallback(Context context){ this.context = context;
 }
 
 public void Callback(String requestContent){
 
 }
 
}


调用方法


HttpRequest.sendPost(cb_url, cb_params, new QhHttpRequestCallback(){
	
	@Override
	public void Callback(String requestContent){
		//Toast.makeText(this.context, "回调结果:"+requestContent, Toast.LENGTH_LONG).show();
	}
	
});



标签: Java

发表评论:

本站由emlog驱动 粤ICP备15042739号