重写X509TrustManager

 1 private static TrustManager myX509TrustManager = new X509TrustManager() { 
 2 
 3     @Override 
 4     public X509Certificate[] getAcceptedIssuers() { 
 5         return null; 
 6     } 
 7 
 8     @Override 
 9     public void checkServerTrusted(X509Certificate[] chain, String authType) 
10     throws CertificateException { 
11     } 
12 
13     @Override 
14     public void checkClientTrusted(X509Certificate[] chain, String authType) 
15     throws CertificateException { 
16     } 
17 };
 1 static public String SendHttpsPOST(String url, List<NameValuePair> param, String data) 
 2 { 
 3         String result = null; 
 4         
 5 
 6         //使用此工具可以将键值对编码成"Key=Value&Key2=Value2&Key3=Value3”形式的请求参数 
 7         String requestParam = URLEncodedUtils.format(param, "UTF-8"); 
 8         try { 
 9             //设置SSLContext 
10             SSLContext sslcontext = SSLContext.getInstance("TLS"); 
11             sslcontext.init(null, new TrustManager[]{myX509TrustManager}, null);
12 
13             //打开连接
14         //要发送的POST请求url?Key=Value&Key2=Value2&Key3=Value3的形式 
15            URL requestUrl = new URL(url + "?" + requestParam); 
16            HttpsURLConnection httpsConn = (HttpsURLConnection)requestUrl.openConnection();
17 
18             //设置套接工厂 
19             httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory());
20 
21             //加入数据 
22             httpsConn.setRequestMethod("POST"); 
23             httpsConn.setDoOutput(true); 
24             DataOutputStream out = new DataOutputStream( 
25                     httpsConn.getOutputStream()); 
26             if (data != null) 
27                 out.writeBytes(data); 
28             
29             out.flush(); 
30             out.close();
31 
32             //获取输入流 
33             BufferedReader in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream())); 
34             int code = httpsConn.getResponseCode(); 
35             if (HttpsURLConnection.HTTP_OK == code){ 
36                 String temp = in.readLine(); 
37                 /*连接成一个字符串*/ 
38                 while (temp != null) { 
39                     if (result != null) 
40                         result += temp; 
41                     else 
42                         result = temp; 
43                     temp = in.readLine(); 
44                 } 
45             } 
46         } catch (KeyManagementException e) { 
47             e.printStackTrace(); 
48         } catch (NoSuchAlgorithmException e) { 
49             e.printStackTrace(); 
50         } catch (MalformedURLException e) { 
51             e.printStackTrace(); 
52         } catch (ProtocolException e) { 
53             e.printStackTrace(); 
54         } catch (IOException e) { 
55             e.printStackTrace(); 
56         }
57 
58         return result; 
59 }

 

posted on 2013-06-24 17:05  曾经的你|  阅读(38297)  评论(2编辑  收藏  举报