URL网络编程

URL网络编程

  • URL:统一资源定位符,它表示Internet上某一资源的位置

URL的组成

<传输协议>://<主机名>:<端口号>/<文件名>#片段名?参数列表

example:http://localhost:8080/xxxxxxxxxxxx#a?username=tom
协议 主机名 端口 资源地址 参数列表

URL常用方法

public static void main(String[] args) {
    try {
        URL url = new URL("https://localhost:8080/hello.txt?username=asuna");
        System.out.println(url.getProtocol());          //协议名
        System.out.println(url.getHost());              //主机名
        System.out.println(url.getPort());              //端口号
        System.out.println(url.getPath());              //文件路径
        System.out.println(url.getFile());              //文件名
        System.out.println(url.getQuery());             //查询名


    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
}

URL下载服务器资源

public static void main(String[] args) {
    HttpURLConnection urlConnection = null;
    InputStream is = null;
    FileOutputStream fos = null;
    try {
        URL url = new URL("http://img.mm4000.com/file/a/26/0f680c3a13_1044.jpg");

        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();
        is = urlConnection.getInputStream();
        fos = new FileOutputStream("InternetProgramming\\cat.jpg");

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

        System.out.println("下载完成");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (urlConnection != null)
            urlConnection.disconnect();
    }
    
}
posted @ 2021-11-20 13:31  叁玖贰拾柒  阅读(11)  评论(0)    收藏  举报