import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.junit.Test;
/**
* URL 统一资源定位符 :
*
* 一个 URL对象 对应着 互联网上的一个资源
*
* 可以通过URL对象 调用其相应的方法 将资源下载。
*
url.getProtocol();//获取url的协议
url.getHost();//获取主机
url.getPort();//获取端口号
url.getPath();//URL对象的 文件路径
url.getFile();//URL对象的 文件名
url.getRef();//URL在文件中的相对位置
url.getQuery();//获取查询条件
* @author Administrator
*
*/
public class TestURL {
@Test
public void testurl() throws Exception{
// 1、创建一个URL对象 类似于File对象
URL url = new URL("http://127.0.0.1:9080/member/admin!login.action?ouid=123");
// 获取 URL对象的协议
System.out.println(url.getProtocol());
// 获取主机名
System.out.println(url.getHost());
// 获取端口号
System.out.println(url.getPort());
// 获取url的文件路径
System.out.println(url.getPath());
// 获取URL对象的 文件名
System.out.println(url.getFile());
// 获取URL在文件中的相对位置
System.out.println(url.getRef());
// 获取查询名
System.out.println(url.getQuery());
}
// 下载 或者读取远程的 文件 音频 文字 文件
@Test
public void getURLContent() throws Exception{
// 1.创建一个URL对象
URL url = new URL("https://www.baidu.com/");
InputStream os = url.openStream();
byte[] b = new byte[1024];
int len;
while((len=os.read(b))!=-1){
String st = new String(b,0,len);
System.out.println(st);
}
os.close();
}
// 与URL对象 建立连接 即能往服务器写(传入服务器中 ) ,,也能从服务器读取文件 (音频。视频 html等 下载下来 )
@Test
public void testInOut() throws Exception{
// 1.创建一个URL对象
URL url = new URL("https://www.baidu.com/");
URLConnection urlcon = url.openConnection();
FileOutputStream fos = new FileOutputStream(new File("baidu.txt"));
InputStream is = urlcon.getInputStream();
byte[] b= new byte[1024];
int len;
while((len=is.read(b))!=-1){
fos.write(b, 0, len);
fos.flush();
}
fos.close();
is.close();
}
}
java 网络编程 URL类 笔记
最新推荐文章于 2023-05-04 17:47:05 发布