使用HttpURLConnection來訪問web頁面。
1
import java.io.BufferedReader;
2
import java.io.IOException;
3
import java.io.InputStreamReader;
4
import java.net.MalformedURLException;
5
import java.net.URL;
6
import java.net.URLConnection;
7
8
9
public class WebPageReader{
10
private static URLConnection connection;
11
private static void connect(String urlString){
12
try {
13
URL url = new URL(urlString);
14
connection = url.openConnection();
15
} catch (MalformedURLException e) {
16
e.printStackTrace();
17
} catch (IOException e) {
18
e.printStackTrace();
19
}
20
}
21
private static void readContents(){
22
BufferedReader in = null;
23
try {
24
in= new BufferedReader(new InputStreamReader(connection.getInputStream()));
25
String inputLine;
26
while((inputLine=in.readLine())!=null){
27
System.out.println(inputLine);
28
}
29
} catch (IOException e){
30
e.printStackTrace();
31
}
32
}
33
public static void main(String[] args){
34
connect("http://www.google.com.hk/webhp?client=aff-cs-360se&ie=utf-8&oe=UTF-8");
35
readContents();
36
}
37
}

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
