java web----URL

时间:2021-04-29 08:11:10

 简单使用

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL; public class Server{
public static void main(String[] args) {
try {
URL url = new URL("https://img2.mtime.com/up/722/1722722/84E2C3E0-DD60-41EA-AAB1-2BDC8A0578AD_500.jpg");
HttpURLConnection coon = (HttpURLConnection) url.openConnection(); BufferedInputStream bis = new BufferedInputStream(coon.getInputStream()); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("C:\\Users\\zhengyan\\Desktop\\test1\\1.jpg"));
byte bytes[] = new byte[1024];
int len;
while ((len=bis.read(bytes))!=-1){
bos.write(bytes,0,len);
}
bis.close();
bos.close();
System.out.println("下载完成");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

使用java URL下载资源

如果出现:javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

原因可能是java中没有安装信任的证书

1、将所需要访问的网站的有效证书下载下来,到任意位置

java web----URL

java web----URL

2、在控制台中输入(最好以管理员模式)

send,为证书文件的名字(下载的时候命名的)  , D:\java\jdk1.8.0_201\jre\lib\security\cacerts,为本机的cacerts路径,  C:\Users\zhengyan\Desktop\send.cer ,为证书的路径

keytool -import -alias send -keystore D:\java\jdk1.8.0_201\jre\lib\security\cacerts  -file C:\Users\zhengyan\Desktop\send.cer

3、重启  java程序