java原生API发送https请求
来源:互联网 发布:为什么美工工资高 编辑:程序博客网 时间:2024/05/14 10:13
一、原生API依赖引用
注意不要引用错误,否则会引发诡异错误。
import javax.net.ssl.HttpsURLConnection;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSocketFactory;import javax.net.ssl.TrustManager;import sun.net.www.protocol.https.Handler;
二、自定义TrainX509TrustManager
import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import javax.net.ssl.X509TrustManager;public class TrainX509TrustManager implements X509TrustManager{ @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }
三、示例代码
public String readURLByHttpsGet(String url, String charset) throws Exception { //发送https前的准备工作 TrustManager[] tm = { new TrainX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); SSLSocketFactory ssf = sslContext.getSocketFactory(); String content = ""; // 尝试连10次 boolean suc = false ; for (int i = 0; i < 10; i++) { try {// URL net = new URL(url);//此法会抛异常 URL net = new URL(null,url,new Handler());//重要,必须要传入new Handler(),否则会抛异常 InputStream in = null; HttpsURLConnection conn = (HttpsURLConnection) net.openConnection();//重要 conn.setSSLSocketFactory(ssf);//重要 conn.setConnectTimeout(60000); conn.setReadTimeout(60000); in = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in, charset)); StringBuffer sb = new StringBuffer(); int ch; while ((ch = br.read()) != -1) { sb.append((char) ch); } in.close(); content = sb.toString(); suc = true; break; } catch (Exception e) { e.printStackTrace(); if (i == 9) { break; } continue; } } if(!suc){ throw new Exception("读取 失败:"+url) ; } return content; }
0 0
- java原生API发送https请求
- java 发送 https请求
- java发送https请求
- java 发送HTTPS请求
- Java---发送HTTPS请求
- 运用原生Java Api发送简单的Get请求、Post请求
- java发送https的请求
- java HttpsURLConnection发送https请求
- JAVA发送http、https请求
- 发送Https请求(Java)
- 发送Https请求(Java)
- java HttpsURLConnection发送https请求
- 使用Java原生API编写发送HTTP_POST请求的工具类
- 使用Java原生API编写发送HTTP_POST请求的工具类
- 使用Java原生API编写发送HTTP_POST请求的工具类
- 使用java 发送https 协议请求
- Java 发送https 的post请求方法
- 使用java发送https的请求
- maven工程子项目消失了怎么办
- opencv学习笔记之读取,修改,保存图像
- leetCode练习(91)
- windows常用软件收集
- Application生命周期
- java原生API发送https请求
- 存储过程介绍
- 判断手机是否支持google play服务
- 100天土鸡饲养计划(72)
- java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
- vmware虚拟机上Redhat5操作系统安装arm-linux-gcc 4.5.1交叉编译环境
- Java集合框架总结
- vs2015编译opencv2.4.10和opencv3.10源码(64位)
- shell中test命令用法详解