永发信息网

如何用JAVA实现HTTPS客户端

答案:1  悬赏:30  手机版
解决时间 2021-03-24 03:48
如何用JAVA实现HTTPS客户端
最佳答案
import java.io.*;
import java.net.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.*;
public class TrustSSL {
private static class TrustAnyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}
private static class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
public static void main(String[] args) throws Exception {
InputStream in = null;
OutputStream out = null;
byte[] buffer = new byte[4096];
String str_return = "";
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
new java.security.SecureRandom());
URL console = new URL(
"https://192.168.1.188/test.php?username=测试");
HttpsURLConnection conn = (HttpsURLConnection) console
.openConnection();
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.connect();
InputStream is = conn.getInputStream();
DataInputStream indata = new DataInputStream(is);
String ret = "";
while (ret != null) {
ret = indata.readLine();
if (ret != null && !ret.trim().equals("")) {
str_return = str_return
+ new String(ret.getBytes("ISO-8859-1"), "GBK");
}
}
conn.disconnect();
} catch (ConnectException e) {
System.out.println("ConnectException");
System.out.println(e);
throw e;
} catch (IOException e) {
System.out.println("IOException");
System.out.println(e);
throw e;
} finally {
try {
in.close();
} catch (Exception e) {
}
try {
out.close();
} catch (Exception e) {
}
}
System.out.println(str_return);
}
}追问你这个是直接信任所有host?追答是的,不过有需要你也可以不都信任,只是个例子把,希望能有用
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
epson 投影机开机后电源灯和旁边指示灯是红色
某卷烟厂为增值税一般纳税人,2014年10月10标
查看自己电脑端口号,语句的特指计算机语句
吉大学生证和洗澡卡丢失能不能补办
单选题人在运动时突然停下来,会造成暂时性的
应婚迁医保和养老保险怎么转
六度寺村怎么去啊,有知道地址的么
一层建筑高度4.2米可以用木模吗
环网室是干什么用的
《童年》中的段落的赏析
在电信手机app中的川号子中选择了一个预存600
工作后还能去考研吗
总装后勤部李光明什么职务
汨罗市岳阳中国银行这个地址怎么能查询到,着
南昌市职业教育校外实训基地地址在什么地方,
推荐资讯
试题类型:阅读理解试题难度:一般更新时间:
短文填空先通读下面的短文,然后根据短文内容
保护办公室环境的标语,保护花草环境标语
淡若天涯是什么意思,天涯赤子心里的歌曲,羞
请问我的车是北京现代领动自动精英版的,有8
步步惊心中四阿哥登基为什么要关若曦
苏辙简介
电脑屏幕突然只剩壁纸 什么都没有了 怎么办?
用套套过的鹧鸪跑了,要多久才能再去套
在买个体养老保险的同时,可以吃低保吗
五年级语文下册27课主要内容
一本书第一天读了全书的20%,第二天读了余下
正方形一边上任一点到这个正方形两条对角线的
阴历怎么看 ?