URL

URL
url(统一资源定位符),通过URL可以从互联网中找到位于Http服务器中的相关资源.

URL构成

http协议://主机地址:端口号/资源地址?查询信息

http://www.softeem.com:80/index?name=XXX&pwd=XXX

一些关于URL的方法:

public class UrlDemo {
	
	public static void main(String[] args) throws Exception {
		
		String path = "http://hk.softeem.top:80/blog/main.jsp?name=admin";
		//根据字符串的url地址构建一个URL对象
		URL url = new URL(path);
		//获取协议部分
		String protocol = url.getProtocol();
		System.out.println(protocol);
		//获取主机地址
		String host = url.getHost();
		System.out.println(host);
		//获取端口
		int port = url.getPort();
		System.out.println(port);
		//获取请求资源
		String path1 = url.getPath();
		System.out.println(path1);
		//获取查询地址(?后面就是查询)
		String  query = url.getQuery();
		System.out.println(query);
		
		//URLConnection是个抽象类
		//打开一个URL连接并且获取一个连接对象
		HttpURLConnection coon = (HttpURLConnection) url.openConnection();
		//设置请求方式
		coon.setRequestMethod("GET");
		//获取请求的数据长度(字节)
		int len = coon.getContentLength();
		System.out.println(len);
		//
		String enc = coon.getContentEncoding();
		System.out.println(enc);
		
		//coon.connect();
		//获取响应状态码(看是否运行成功)
		int code = coon.getResponseCode();
		if(code == HttpURLConnection.HTTP_OK){
			InputStream is = coon.getInputStream();
			//字节输入流转换成字符输入流
			InputStreamReader isr = new InputStreamReader(is,"utf-8");//这里的utf-8字符编码.
			//缓冲流
			BufferedReader br = new BufferedReader(isr);
			//因为的文本是一行,因此想到用bufferedRead
			String data = br.readLine();
			System.out.println(data);
			}	
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值