网络编程(四)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