java为网络支持提供java.net包,该包下的URL和URLConnection等类提供了以编程方式访问Web服务端的功能。
URL(unifo resource locator)对象代表统一资源定位器,它是指向互联网“资源”的指针。资源可以是简单的文件或目录,也可以是对更为复杂对象的引用,例如对数据库或搜索引擎的查询。在通常情况下,URL可以由协议名,主机,端口和资源组成,即满足如下格式:
prptocol://host:port/resourceName
例如如下的URL地址:
http://www.crazyit/index.php
URL对象提供的openStream()方法可以读该URL资源的InputStream,通过该方法可以非常方便的读取远程资源。
demo:
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String str = "http://192.168.1.100:8080/myweb/1.html?name=lisi";
URL url = new URL(str);
System.out.println("getProtocol"+url.getProtocol());//获取该URL的协议名称
System.out.println("getFile"+url.getFile());//获取该URL的资源名
System.out.println("getHost"+url.getHost());//获取该URL的主机名
System.out.println("getPath"+url.getPath());//获取该URL的路径
System.out.println("getPort"+url.getPort());//获取该URL的端口号
System.out.println("getQuery"+url.getQuery());//获取该URL的查询字符串部分
/*InputStream in = url.openStream();
byte[] burf = new byte[1024];
int len = in.read(burf);
String text = new String(burf,0,len);
System.out.println(text);
in.close();*/
}
运行结果: