URL下载网络资源
程序员文章站
2022-05-05 20:39:39
...
1.获取目标的URL的相关属性
public class URLDemo01 {
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=kuangshen&password=123");
System.out.println(url.getProtocol());//协议
System.out.println(url.getHost());//主机ip
System.out.println(url.getPort());//端口
System.out.println(url.getPort());//文件
System.out.println(url.getFile());//全路径
System.out.println(url.getQuery());//参数
}
}
2.下载指定的URL地址的资源
public class UrlDown {
public static void main(String[] args) throws Exception {
//1.下载地址
URL url = new URL("http://localhost:8080/dalei/dalei.txt");
//2.连接到这个资源 http
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("dalei.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();//断开连接
}
}
上一篇: URL 获取网络资源
下一篇: URL读取网络资源