網絡編程(四)URL實現下載資源


1.8、URL

https://www.cnblogs.com/qkshhan/

統一資源定位符:定位資源的,定位互聯網上的某一個資源。

DNS域名解析 www.baidu.com xxx.x..x..x

協議://ip端口:端口/項目名/資源
package comip.study.lesson04;

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

//http://localhost:8080/hansuo/secret.txt

public class URLDemo01 {
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=kuangshen$passworld=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 comip.study.lesson04;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class UrlDown {
    public static void main(String[] args) throws IOException {
        //1.下載地址
        URL url = new URL("http://localhost:8080/hansuo/secret.txt");

        //連接到這個資源 http
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        InputStream inputStream = urlConnection.getInputStream();

        FileOutputStream fos = new FileOutputStream("secret.txt");

        byte[] buffer = new byte[1024];
        int len;
        while ((len=inputStream.read(buffer))!=-1){
            fos.write(buffer,0,len);//寫出這個數據
        }

        fos.close();
        inputStream.close();
        urlConnection.disconnect();//斷開連接
    }
}

記得我們我們需要提前在此處創建好問哦們需要下載的東西。

image

可以訪問到文件

image

沒有默認資源index.jsp

image

下載成功!

image


免責聲明!

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



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