Java学习之路--网络编程相关04

发布时间 2023-09-20 16:22:51作者: 寂灭无言
package com.kuang.lesson04;

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

//2023.3.8/9 URL 下载网络资源
public class URLDemo01 {
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("https://localhost:8080/helloworld/index.jsp?usename=caidingchao&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 com.kuang.lesson04;

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

//2023.3.10 URL 下载文件资源
public class URLDown {
public static void main(String[] args) throws Exception {
//1.下载地址
URL url = new URL("http://localhost:8080/CaiDingChao/study.txt");

//2.连接到这个资源 HTTP
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

InputStream inputStream = httpURLConnection.getInputStream();

FileOutputStream fileOutputStream = new FileOutputStream("study.txt");

byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer))!= -1){
fileOutputStream.write(buffer,0,len);//写出这个数据
}

fileOutputStream.close();
inputStream.close();
httpURLConnection.disconnect();
}
}