12.URL下载网络资源

  1. URL:同一资源定位符、定位资源的,定位互联网上的某一个资源
  2. DNS:域名解析、相当于把 www.baidu.com 解析成 xxx.x..x..x这样一个ip、所以说本质它还是个ip,域名只是为了好记。映射的过程叫DNS、域名解析。
  3. https是43端口,正常http是80端口

1、正常的URL由下面5部分组成,可以少,但不能多。
1 协议://ip地址:端口号/项目名/资源
2、得学习一个类:URL类
 1 package com.inet.lesson4;
 2 
 3 import java.net.MalformedURLException;
 4 import java.net.URL;
 5 
 6 public class URLDemo01 {
 7     public static void main(String[] args) throws MalformedURLException {
 8         URL url = new URL("http://localhost:8080/helloword/index.jsp?username=duanfu&password=123");
 9          System.out.println(url.getProtocol());//协议
10         System.out.println(url.getHost());//主机ip
11         System.out.println(url.getPort());//端口
12         System.out.println(url.getPath());//文件地址
13         System.out.println(url.getFile());//文件全路径
14         System.out.println(url.getQuery());//参数
15     }
16 }
17 
18 结果:
19 http
20 localhost
21 8080
22 /helloword/index.jsp
23 /helloword/index.jsp?username=duanfu&password=123
24 username=duanfu&password=123
3、访问一下,利用Tomcat:
  1. 在解压的Tomcat下的webapps下建立一个leiwei文件夹,里面新建一个SecurityFile.txt,写一行字你被玩了2.去bin目录下打开startup.bat,启动Tomact3.打开浏览器访问资源
4、想办法下载网络资源,SecurityFile.txt
 1 package com.inet.lesson4;
 2 
 3 import java.io.FileOutputStream;
 4 import java.io.InputStream;
 5 import java.net.HttpURLConnection;
 6 import java.net.URL;
 7 
 8 public class UrlDown {
 9     public static void main(String[] args) throws Exception {
10         //1.下载地址
11         URL url = new URL("http://localhost:8080/leiwei/SecurityFile.txt");
12 
13         //2.连接到这个资源
14         HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
15 
16         InputStream inputStream = urlConnection.getInputStream();
17 
18         FileOutputStream fos = new FileOutputStream("SecurityFile.txt");
19 
20         byte[] buffer = new byte[1024];
21         int len;
22         while ((len = inputStream.read(buffer)) != -1) {
23             fos.write(buffer, 0, len);//写出这个数据
24         }
25 
26         fos.close();
27         inputStream.close();
28         urlConnection.disconnect();//断开连接
29     }
30 }

posted @ 2020-03-30 18:24  断浮  阅读(387)  评论(0编辑  收藏  举报