URL是将网址面向对象,方便了对网址信息的操作,连接,以及接收数据
我们可以利用这种方法抓取到网页上的信息
public static void main(String[] args) throws IOException {
String path ="http://localhost:8080/myweb/mail.html?name=kk";
URL url =new URL(path);//同一资源定位符
System.out.println(url.getProtocol());//得到协议
System.out.println(url.getHost());
System.out.println(url.getPort());
System.out.println(url.getPath());//得到资源路径 /myweb/mail.html
System.out.println(url.getFile());// /myweb/mail.html?name=kk
//和服务器端连接
URLConnection conn = url.openConnection();
//读取服务器返回的mail.html页面的数据
InputStream in = conn.getInputStream();
byte[] arr = new byte[1024];
int len = in.read(arr);
System.out.println(new String(arr,0,len));
}