HttpsURLConnection添加SSL认证
来源:互联网 发布:中国指数研究院 知乎 编辑:程序博客网 时间:2024/05/17 23:08
代码如下,注释已经很清晰
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.util.Log;
public class MyHttpPost {
public static String sendPost(String stringUrl, String params) { byte[] bytes = params.toString().getBytes(); try { URL url = new URL(stringUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 读取服务器要验证的cer证书 connection.setSSLSocketFactory(setCertificates(ZeepsonApplication.getContext().getAssets().open("server.cer"))); // 设置不验证服务器,返回true不验证,false为验证,默认为false;也可以根据arg0的值验证或不验证指定服务器; connection.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }); connection.setConnectTimeout(30000); connection.setDoInput(true);// 打开输入流,默认情况下是true connection.setDoOutput(true);// 打开输出流 ,需要设为true, 默认情况下是false connection.setRequestMethod("POST"); connection.setUseCaches(false);// 使用post方式不能使用缓存 // 设置请求体类型为文本类型 connection.setRequestProperty("Content-Type", "application/json"); // 设置请求体 的长度 connection.setRequestProperty("Content-Length", String.valueOf(bytes.length)); // 获得输出流,向服务器写入 // getOutputStream中包含了connect,所以不用调用connect也可以 OutputStream outputStream = connection.getOutputStream(); outputStream.write(bytes); int response = connection.getResponseCode();// 获取响应码 Log.i("**********响应码***********", "响应码:" + response); if (response == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream();// 获取输入流 BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); return responseResult(br);// 处理接收到的数据 } } catch (Exception e) { e.printStackTrace(); return "{\"type\":\"error\",\"code\":0,\"message\":\"发送请求出现错误\",\"data\":null}"; } return "{\"type\":\"error\",\"code\":0,\"message\":\"连接超时\",\"data\":null}";}private static String responseResult(BufferedReader br) { String line = null; StringBuffer sb_response = new StringBuffer(); try { while ((line = br.readLine()) != null) { sb_response.append(line); } } catch (Exception e) { e.printStackTrace(); } String ret = new String(sb_response); return ret;}public static SSLSocketFactory setCertificates(InputStream... certificates){ try{ //证书工厂。此处指明证书的类型 CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); //创建一个证书库 KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); int index = 0; for (InputStream certificate : certificates){ String certificateAlias = Integer.toString(index++); //将证书导入证书库 keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate)); try{ if (certificate != null) certificate.close(); } catch (IOException e){ e.printStackTrace() ; } } //取得SSL的SSLContext实例 SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManagerFactory trustManagerFactory = TrustManagerFactory. getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); //初始化keystore KeyStore clientKeyStore = KeyStore.getInstance("BKS"); clientKeyStore.load(ZeepsonApplication.getContext().getAssets().open("client1.bks"), "123456".toCharArray()); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(clientKeyStore, "123456".toCharArray()); // 第一个参数是授权的密钥管理器,用来授权验证。TrustManager[]第二个是被授权的证书管理器,用来验证服务器端的证书。第三个参数是一个随机数值,可以填写null sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
// sslContext.init(null, null, new SecureRandom());
return sslContext.getSocketFactory() ;
} catch (Exception e){ e.printStackTrace(); } return null ;}
}
参考:http://blog.csdn.net/lmj623565791/article/details/48129405
阅读全文
0 0
- HttpsURLConnection添加SSL认证
- Android SSL双向认证HttpsURLConnection
- 添加SSL认证信息
- 为HttpsURLConnection添加信任证书
- HttpsURLConnection实现SSL的GET/POST请求
- HttpsURLConnection实现SSL的GET/POST请求
- https HttpsURLConnection请求的单向认证
- HttpsURLConnection
- HttpsURLConnection
- java给HttpsURLConnection添加信任证书
- HttpURLConnectionImpl cannot be cast to javax.net.ssl.HttpsURLConnection
- 关于双向认证,使用HttpsURLConnection访问Https安全链接
- 配置Tomcat SSL认证...
- Tomcat配置SSL认证
- Tomcat6 ssl 双向认证
- java ssl 双向认证
- TOMCAT配置SSL认证
- SSL单向、双向认证
- springmvc
- pycharm开发scrapy项目中的一些问题
- java中的保留字和关键字可能对零基础的有用
- C语言:求素数
- ios学习笔记一之Object-c基础
- HttpsURLConnection添加SSL认证
- 五大通信设备厂商:华为存隐忧,中兴已掉队
- 高效开发Android工具和网址
- 机器学习1:回归(regression)
- Deprecated: Automatically populating $HTTP_RAW_POST_DATA is deprecated and will be removed in a futu
- 结构体与位域的对齐
- Jenkins之系统设置
- Hadoop好友推荐系统-组别数据入库
- 自用基础