您的位置:首页 > 其它

URL

2015-07-22 22:37 337 查看
URL:URL(Uniform Resource Locator)是统一资源定位符的简称,它表示Internet上某一资源的地址。通过URL我们可以访问Internet上的各种网络资源,比如最常见WWW,FTP站点。浏览器通过解析给定的URL可以在网络上查找相应的文件或其他资源。

import java.net.MalformedURLException;
import java.net.URL;

/*
* URL常用方法
*/
public class Test02 {
public static void main(String[] args) {
try {
//创建一个URL实例
URL imooc=new URL("http://www.baidu.com");
//?后面表示参数,#后面表示锚点
URL url=new URL(imooc, "/index.html?username=tom#test");
System.out.println("协议:"+url.getProtocol());
System.out.println("主机:"+url.getHost());
//如果未指定端口号,则使用默认的端口号,此时getPort()方法返回值为-1
System.out.println("端口:"+url.getPort());
System.out.println("文件路径:"+url.getPath());
System.out.println("文件名:"+url.getFile());
System.out.println("相对路径:"+url.getRef());
System.out.println("查询字符串:"+url.getQuery());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}


获取网站页面源码

package network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class Urlconnection3 {
public static void main(String[] args) throws IOException {
URL url=new URL("http://www.sohu.com");

BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream()));

String line=null;

while(null!=(line=br.readLine())){
System.out.println(line);
}

br.close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: