java web----URL類使用


 簡單使用

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、將所需要訪問的網站的有效證書下載下來,到任意位置

 

 

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程序


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM