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,启动Tomact
    3.打开浏览器访问资源
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 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值