您的位置:首页 > 编程语言

URL编程

2021-06-22 01:32 726 查看

URL类
URL(Uniform Resource Locator):统一资源定位符,它表示 Internet 上 某一
资源的地址。
它是一种具体的URI,即URL可以用来标识一个资源,而且还指明了如何locate
这个资源。
通过 URL 我们可以访问 Internet 上的各种网络资源,比如最常见的 www,ftp
站点。浏览器通过解析给定的 URL 可以在网络上查找相应的文件或其他资源。
 URL的基本结构由5部分组成:
< 传输协议>://< 主机名>:< 端口号>/< 文件名># 片段名? 参数列表
例如:
http://192.168.1.100:8080/helloworld/index.jsp#a?username=shkstart&password=123
#片段名:即锚点,例如看小说,直接定位到章节
参数列表格式:参数名=参数值&参数名=参数值....

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

package com.atguigu.java1;

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

/**
* URL网络编程
* 1.URL:统一资源定位符,对应着互联网的某一资源地址
* 2.格式:
*  http://localhost:8080/examples/beauty.jpg?username=Tom
*  协议   主机名    端口号  资源地址           参数列表
*
* @author CH
* @create 2021 下午 4:47
*/
public class URLTest {

public static void main(String[] args) {

try {

URL url = new URL("http://localhost:8080/examples/beauty.jpg?username=Tom");

//            public String getProtocol(  )     获取该URL的协议名
System.out.println(url.getProtocol());
//            public String getHost(  )           获取该URL的主机名
System.out.println(url.getHost());
//            public String getPort(  )            获取该URL的端口号
System.out.println(url.getPort());
//            public String getPath(  )           获取该URL的文件路径
System.out
56c
.println(url.getPath());
//            public String getFile(  )             获取该URL的文件名
System.out.println(url.getFile());
//            public String getQuery(   )        获取该URL的查询名
System.out.println(url.getQuery());

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

}

}

 

 

 

 

package com.atguigu.java1;

import java.io.FileOutputStream;
import java.io.IOException;
im
ad0
port java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
* @author CH
* @create 2021 下午 4:54
*/
public class URLTest1 {

public static void main(String[] args) {

HttpURLConnection urlConnection = null;
InputStream is = null;
FileOutputStream fos = null;
try {
URL url = new URL("http://localhost:8080/examples/beauty.jpg");

urlConnection = (HttpURLConnection) url.openConnection();

urlConnection.connect();

is = urlConnection.getInputStream();
fos = new FileOutputStream("day10\\beauty3.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(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(urlConnection != null){
urlConnection.disconnect();
}
}

}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: