例子1
package add.socket.url;
import java.net.MalformedURLException;
import java.net.URL;
public class URLTest01 {
public static void main(String[] args) {
try {
URL myURL = new URL(
"http://java.sun.com:80/docs/books/tutorial/index.html#DOWN");
/*
* URL myURL = new URL( "http://www.baidu.com");
*/
String protocal = myURL.getProtocol();
System.out.println("protocal = " + protocal); // protocal = http
String host = myURL.getHost();
System.out.println("host = " + host); // host = java.sun.com
int port = myURL.getPort();
System.out.println("port = " + port); // port = 80
String file = myURL.getFile();
System.out.println("file = " + file); // file =
// /docs/books/tutorial/index.html
String ref = myURL.getRef();
System.out.println("ref = " + ref); // ref = DOWN
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
例子2:
package add.socket.url;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
public class UrlConnection01 {
/**
* 为获得URL的实际比特或内容信息,用它的openConnection()方法从它创建一个URLConnection对象,
* 与调用URL对象相关,它返回一个URLConnection对象。它可能引发IOException异常。
* URLConnection是访问远程资源属性的一般用途的类。
* @throws IOException
*/
public static void main(String[] args) throws IOException {
URL url = new URL("http://localhost:8080/day09/testParam.html");
/* // 打开连接
URLConnection conn = url.openConnection();
// 得到输入流
InputStream is = conn.getInputStream();*/
//上面两句等价于下面的一句,
InputStream is = url.openStream();
// 关于IO流的用法和写法一定要熟悉
OutputStream os = new FileOutputStream("e:\\baidu.txt"); //如果没有可创建文件
byte[] buffer = new byte[2048];
int length = 0;
//将访问的网页写入文件
while (-1 != (length = is.read(buffer, 0, buffer.length)))
{
os.write(buffer, 0, length);
}
is.close();
os.close();
}
}
例子3
package add.socket.url;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class UrlConnection03 {
public static void main(String[] args) throws IOException {
URL url = new URL("http://localhost:8080/day09/testParam.html");
BufferedReader br = new BufferedReader(new InputStreamReader(
url.openStream()));
/* 如果需要转码
* BufferedReader br = new BufferedReader(new InputStreamReader(
url.openStream(), "utf-8")); */
String line = null;
while(null != (line = br.readLine())){
System.out.println(line);
}
br.close();
}
}