該程序只是簡單模擬瀏覽器往網站服務器發送HTTP請求包,然後獲取網站服務器發回的數據包。分別通過兩種方法獲取:
1. 利用Socket與百度服務器建立連接,併發送HTTP請求包獲取:
主要流程:利用InetAddress獲取百度服務器IP --> 通過Socket與服務器建立連接 --> 獲取Socket的輸入輸出流 --> 往服務器發送HTTP請求包 --> 等待服務器發回數據包,收到後保存到制定文件中 --> 關閉連接和流。
源代碼:
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 | import java.io.*; import java.net.*;
/**
* 利用Socket獲取百度的HTTP應答包和HTML數據包
* */ public class SimpleBrowser {
public static void main(String[] args) throws UnknownHostException, IOException {
/****************獲取百度任意一臺服務器的IP****************/
InetAddress getIP = InetAddress.getByName( "www.baidu.com" );
String netIP = getIP.getHostAddress();
System.out.println( "獲取到的網站IP:" + netIP);
/**************************************************/
//利用Socket與其建立TCP連接
Socket s = new Socket(InetAddress.getByName(netIP), 80 );
/**************建立流用於發送和獲取數據**********************/
//獲取輸入流,讀取服務器發回的數據
BufferedReader br = new BufferedReader( new InputStreamReader(s.getInputStream()));
//往網站發數據的輸出流
PrintWriter pw = new PrintWriter( new OutputStreamWriter(s.getOutputStream()), true );
//把網站發回的數據保存到文件的寫入流
PrintWriter savefile = new PrintWriter( new FileWriter( "baidu.txt" ), true );
//發送HTTP請求包的內容
pw.println( "GET / HTTP/1.1" );
pw.println( "Accept: text/html, application/xhtml+xml, */*" );
pw.println( "Accept-Language: zh-CN" );
pw.println( "User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)" );
pw.println( "Host: " + netIP + ":80" );
pw.println( "DNT: 1" );
pw.println( "Connection: closed" );
pw.println();
pw.println();
/**************************************************/
/**************寫入數據*******************************/
String data;
System.out.println( "Waiting..." );
while ((data = br.readLine()) != null ) {
savefile.println(data);
}
/**************************************************/
System.out.println( "獲取結束!!!" );
pw.close();
br.close();
s.close();
savefile.close();
} } |
獲取的文件內容:
2、利用URL獲取:
Java中封裝了URL類,方便解析、操作各種鏈接,同時可以打開鏈接並與其進行通信,所以可以利用URL類獲取數據包,但是利用該方法無法獲取HTTP包的應答數據,但是操作與第一種方法簡單了很多。
主要流程:利用URL綁定一個鏈接 --> 執行openConnection打開連接 --> 獲取輸入流
--> 通過輸入流獲取信息。
源代碼:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import java.io.*; import java.net.*;
public class URLDemo {
public static void main(String[] args) throws IOException {
URLConnection c = url.openConnection(); //打開連接並將其建立的連接對象傳給URLConnection對象
/*
* 利用URL建立的連接獲取百度發回的HTTP應答包
* */
PrintWriter pw = new PrintWriter( new OutputStreamWriter(System.out), true );
InputStream txt = c.getInputStream();
int len = 0 ;
byte [] buf = new byte [ 1024 ];
while ((len = txt.read(buf)) != - 1 ) {
pw.println( new String(buf, 0 ,len));
}
pw.close();
txt.close();
} |