Java 网络编程——URL

URL类是java.net包中的一个重要的类。一个URL对象封装着一个具体的资源引用。URL对象通常包含最基本的三部分信息:协议、地址和资源。

URL的构造方法

方法一:public URL(String str) throws MalformedURLException. 该构造方法使用字符串初始化一个URL对象。
1
2
3
4
5
try{
URL url = new URL("http://www.baidu.com");
}catch(MalformedURLException e){
System.out.println(e);
}
方法二:public URL(String protocol, String host, String file) throws MalformedURLException。该构造方法使用的协议、地址和资源分别由protocol、host和file指定。
1
2
3
4
5
try{
URL url = new URL(protocol,host,file);
}catch(MalformedURLException e){
System.out.println(e);
}

读取URL中的资源

URL 对象调用InputStream openStream()方法可以返回一个输入流,该输入流指向URL对象所包含的资源。

程序代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Scanner;

public class ReadUrl {

private static Scanner in;

public static void main(String[] args) {
in = new Scanner(System.in);
Thread readurl;
URL url;
Look look = new Look();
System.out.println("请输入URL,例如:http://www.baidu.com:");
String string = in.nextLine();
// System.out.println("请输入URL协议:");
// String protocol = in.next();
// System.out.println("请输入URL地址:");
// String host = in.next();
try{

url = new URL(string);
// url = new URL(protocol,host,"");
look.setURL(url);
readurl = new Thread(look);
readurl.start();
}catch(Exception e){
System.out.println(e);
}
}

}

class Look implements Runnable{

URL url;
public void setURL(URL url) {
this.url=url;
}
@Override
public void run() {
// TODO Auto-generated method stub
try{
InputStream inputStream = url.openStream();
byte [] bs = new byte[1024];
int n = -1;
while((n=inputStream.read(bs))!=-1){
String string = new String(bs, 0, n);
System.out.println(string);
}
}catch(IOException e){}
}

}