1. 程式人生 > 其它 >URL下載網路資源

URL下載網路資源

URL統一資源定位符

五大部分:

協議://IP:埠/專案名/資源

package inet;

import java.net.MalformedURLException;
import java.net.URL;

public class URLDemo1 {
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=kuangshen&password=123");
        System.out.println(url.getProtocol());//協議名
        System.out.println(url.getHost());//主機ip
        System.out.println(url.getPort());//埠
        System.out.println(url.getPath());//檔案
        System.out.println(url.getFile());//檔案全路徑
        System.out.println(url.getQuery());//引數
    }
}

下載網路資源

package inet;

import java.io.FileOutputStream;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class URLDown {
    public static void main(String[] args) throws Exception {

        //1.下載地址
        URL url = new URL("https://www.cnblogs.com/kakafa/p/15019311.html");
        //2.連線到這個資源 http連線
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();

        InputStream is= connection.getInputStream();

        FileOutputStream fos = new FileOutputStream("E:\\2021.TXT");

        byte[] buffer=new byte[1024];
        int len=0;
        while((len=is.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }

        fos.close();
        is.close();
        connection.disconnect();//斷開連線

    }
 }