java 网络编程 URL类 笔记

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();
	}
	
	
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

prefectjava

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值