java端访问https

     java端是指使用java访问https的链接,由于https是通过证书认证的,所以直接访问的话是会报错的,想要访问需要下载证书,放入到jdk中,接下来讲述一下具体步骤。
    以chrome为例,点击链接前面的绿色锁–》详细信息–》view certificate–》证书详细信息–》导出证书。浏览器不一样可能会导致步骤有些不同。
    接下来将证书导入到jdk中,在cmd中打开jdk的jre/lib目录,输入以下命令
     keytool -import -alias cacerts -keystore cacerts -file E:\onecc.cer -trustcacerts
    若提示输入密码,则输入changeit,此为默认密码
    至此,将证书导入到jdk的证书库中。如果想要打开别的https网站,则需要重复导证书。
    如果执行代码过程中报了403的错误,则是由于网站禁止使用java端打开,需要在代码中添加以下内容
     HttpURLConnection connection = (HttpURLConnection) url.openConnection();
     connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
    最后的是一点java代码,将页面下载到本地,注释的部分忽略。

public static void getHtml(String path){
String urlPath = “https://www.biquku.co/337751/” + path + “.html”;
InputStream in = null;
OutputStream out = null;
try {
URL url = new URL(urlPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty(“User-Agent”, “Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)”);
in = new BufferedInputStream(connection.getInputStream());
out = new BufferedOutputStream(new FileOutputStream(“D:\test\1.txt”, true));
byte[] bytes = new byte[1024];
int len = 0;
StringBuilder sb = new StringBuilder();
while((len = in.read(bytes)) != -1) {
//sb.append(new String(bytes,0,len));
out.write(bytes,0,len);
}
/* String[] splits = sb.toString().split("<div id=\“content\”>");
String content = “”;
if(splits.length > 1) {
content = splits[1];
}
Matcher matcher = Pattern.compile(“A3.html").matcher(content);
if(matcher.find()){
System.out.println(matcher.group());
}
content = content.split("")[0];
content = content.replaceAll("    “,”");
content = content.replaceAll("<br[ /]
>”,"\n");
out.write(content.getBytes());*/
} catch (Exception e) {
e.printStackTrace();
} finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

吐槽哈使用代码块就成一行了…大家将就着看一下吧。
除了上方介绍的导入证书外,还有其他的方式,感兴趣的看一下这篇:
https://blog.csdn.net/qq_32133405/article/details/84100858

文章的最后放一点点的东西
公众号:暗月的小木屋
GitHub:https://github.com/anyueStarrysky/Cabins

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值