Java访问Https接口

本文详细介绍了如何使用Java访问HTTPS接口,包括建立连接、发送数据和接收返回数据的具体步骤。文章通过实例展示了如何配置SSL环境并实现数据的安全传输。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java访问https接口、发送数据、接收数据

1.建立连接

 1 URL url = new URL(urlStr);
 2 //创建SSLContext对象,并使用我们指定的信任管理器初始化
 3 TrustManager[] tm = {new MyX509TrustManager ()}; 
 4 //SSLContext.getInstance(arg0, arg1),注意arg0要与要访问的https接口网站所用的TLS/SSL的版本一致,否则在打开连接时会报握手失败的错            
 5 SSLContext sslContext =SSLContext.getInstance("TLSv1.2","SunJSSE"); 
 6 sslContext.init(null, tm, new java.security.SecureRandom()); 
 7 //从上述SSLContext对象中得到SSLSocketFactory对象
 8 SSLSocketFactory ssf = sslContext.getSocketFactory();
 9 //创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
10 HttpsURLConnection urlCon = (HttpsURLConnection)url.openConnection();
11 urlCon.setSSLSocketFactory(ssf);

2.向https接口发送数据

String str = "xxx";//你要发送的数据
byte[] reqData = str.getBytes();
urlCon.setDoOutput(true);
urlCon.setDoInput(true);
urlCon.setUseCaches(false);
urlCon.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
urlCon.setRequestProperty("Content-length", String.valueOf(reqData.length)); 
DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
printout.write(reqData);
printout.flush();
printout.close();

3.接收https接口返回的数据

 1 DataInputStream input = null;
 2 java.io.ByteArrayOutputStream out = null;
 3 input = new DataInputStream(urlCon.getInputStream());
 4 out = new java.io.ByteArrayOutputStream();
 5 byte[] bufferByte = new byte[256];
 6 int l = -1;
 7 int downloadSize = 0;
 8 while ((l = input.read(bufferByte)) > -1) {
 9     downloadSize += l;
10     out.write(bufferByte, 0, l);
11     out.flush();
12 }
13 String resData = out.toString();

 

转载于:https://www.cnblogs.com/kylyww/p/8191456.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值