URl

统一资源定位符:定位互联网上的某一个资源

http://www.baidu.com/
1.协议://IP地址:端口/项目名/资源

URLDemo01

package com.guo.lesson04;

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

public class URLDemo01 {
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("https://localhost:8080/helloworld/index.jsp?username=chenguo&password=123");

        System.out.println(url.getProtocol());//https   协议
        System.out.println(url.getHost());//localhost  主机ip
        System.out.println(url.getPort());//8080       端口
        System.out.println(url.getPath());// /helloworld/index.jsp     文件
        System.out.println(url.getFile());// /helloworld/index.jsp?username=chenguo&password=123   全路径
        System.out.println(url.getQuery());//username=chenguo&password=123   参数
    }
}

URLDown

package com.guo.lesson04;

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 {
        //下载地址
        URL url = new URL("https://cn.bing.com/images/search?view=detailV2&ccid=CBIdxYPr&id=5EF80F6095F92A43A72B71CC3FA43DA4BFCE886A&thid=OIP.CBIdxYPrkF2i5CUfC9tTJAHaKk&mediaurl=https%3A%2F%2Fwww.renwuji.com%2Fwp-content%2Fuploads%2Fimages%2F2023%2F01%2F17%2F9317d0888fb84d589e3a2881ea001c89~noop_suxznfsdpxp.jpg&exph=1541&expw=1080&q=%E8%82%96%E6%88%98&form=IRPRST&ck=282DE07C85B29FAB9E070D5638DE1B66&selectedindex=0&itb=0&cw=1519&ch=894&ajaxhist=0&ajaxserp=0&cdnurl=https%3A%2F%2Fts1.tc.mm.bing.net%2Fth%2Fid%2FR-C.08121dc583eb905da2e4251f0bdb5324%3Frik%3DaojOv6Q9pD%252fMcQ%26pid%3DImgRaw%26r%3D0&vt=0&sim=11");
        //连接到这个资源
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        InputStream inputStream = urlConnection.getInputStream();

        FileOutputStream fos = new FileOutputStream("9317d0888fb84d589e3a2881ea001c89~noop_suxznfsdpxp.jpg");

        byte[] buffer = new byte[1024];
        int len;
        while ((len=inputStream.read(buffer))!=-1) {
            fos.write(buffer,0,len);
        }
        fos.close();
        inputStream.close();
        urlConnection.disconnect();//断开连接
    }
}

posted @ 2026-03-19 20:31  果子同志  阅读(37)  评论(0)    收藏  举报