欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Url基础方法实现

程序员文章站 2022-04-03 08:33:30
...

Url基础方法实现

点击查看   URI    API

 

package com.chen.study.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class UrlTest {

	public static void main(String[] args) {
		try {
			URL baidu = new URL("http://www.baidu.com");
			URL url = new URL(baidu,"/search/?words=socket");
			URLConnection myurlcon = url.openConnection(); 
			myurlcon.setConnectTimeout(1000);   //设置连接超时
			myurlcon.setReadTimeout(1000);   //设置响应超时
			
			System.out.println("地址:"+url.getHost());
			System.out.println("资源:"+url.getPath());
			System.out.println("端口:"+url.getPort());
			System.out.println("协议:"+url.getProtocol());
			System.out.println("查询字段:"+url.getQuery());
			System.out.println("锚点:"+url.getRef());
			
			/*
			 *获取网站的所有内容 
			 */
			InputStream is = baidu.openStream(); //获取字节流
			BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8")); //字节流转字符流并存入缓冲
			
			String info = br.readLine();
			while(info!=null){
				System.out.println(info);
				info = br.readLine();
			}
			//关闭连接
			br.close();
			is.close();
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

 

相关标签: URL