2010-12-01 59 views
2

晚上好大家
我想在Java中使用Socket類來獲取一個網頁,我已經做到了這一點作爲使用Java Socket類

import java.net.*; 
import java.io.*; 

class htmlPageFetch{ 
     public static void main(String[] args){ 
       try{ 
         Socket s = new Socket("127.0.0.1", 80); 
         DataInputStream dIn = new DataInputStream(s.getInputStream()); 
         DataOutputStream dOut = new DataOutputStream(s.getOutputStream()); 
         dOut.write("GET /index.php HTTP/1.0\n\n".getBytes()); 
         boolean more_data = true; 
         String str; 
         while(more_data){ 
           str = dIn.readLine(); 
if(str==null) 
more_data = false; 
           System.out.println(str); 
         } 
       }catch(IOException e){ 

       } 
     } 
} 

獲取一個網頁,但它只是給空的。

輸出

HTTP/1.1 302 Found 
Date: Wed, 01 Dec 2010 13:49:02 GMT 
Server: Apache/2.2.11 (Unix) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8k PHP/5.2.9 mod_apreq2-20051231/2.6.0 mod_perl/2.0.4 Perl/v5.10.0 
X-Powered-By: PHP/5.2.9 
Location: http://localhost/xampp/ 
Content-Length: 0 
Content-Type: text/html 

null 

回答

2

我不知道這是否是引起您的問題,但HTTP預計,換行回車和換行:

dOut.write("GET /index.php HTTP/1.0\r\n\r\n".getBytes()); 

而且,它不會傷害沖洗並關閉DataOutputStream類:

dOut.flush(); 
dOut.close(); 

如果你打算使用此代碼不僅僅是連接到簡單的測試案例更做任何事情,我會使用,而不是在一個插座自己implenting HTTP HttpURLConnection的這個建議。否則,結果將不僅僅包含網頁。它還將包含HTTP響應,包括狀態碼和標題。你的代碼需要解析。

更新:

看着你添加的響應,與位置沿302響應:頭表示你正在尋找的頁面搬到http://localhost/xampp/(見HTTP 302),並不再有任何內容在原始網址。這可以設置爲由HttpURLConnection或其他庫如Apache HttpClient自動處理。您需要解析狀態碼,解析標題,打開一個新的套接字到響應位置並獲取頁面。根據您的任務的確切要求,您可能還需要熟悉HTTP 1.0 SpecificationHTTP 1.1 Specification

+0

雅拉茲這是真的,但我想這樣做使用套接字,因爲它是我的任務分析收到的輸出 – codeomnitrix 2010-12-01 13:59:28

1

我想代碼工作,也許除了你沒有看到輸出,因爲它是由所有的null是你打印淹沒。你應該在第一個null之後停下來。 更一般地說,DataInputStreamDataOutputStream不適合這份工作。試試這個代碼。

public static void main(String[] args) throws IOException { 
    Socket s = new Socket("127.0.0.1", 80); 
    BufferedReader dIn = new BufferedReader(new InputStreamReader(s.getInputStream())); 
    PrintStream dOut = new PrintStream(s.getOutputStream()); 
    dOut.println("GET /index.php HTTP/1.0"); 
    dOut.println(); 
    String str = null; 
    do { 
     str = dIn.readLine(); 
     System.out.println(str); 
    } while (str != null); 
} 
+0

嘿弗拉維奧雅正在工作,但我無法看到整個頁面的內容。只有「標題」顯示給我,然後「空」我已經將輸出添加到問題。請檢查這個 – codeomnitrix 2010-12-01 13:51:34

0

爲什麼直接使用套接字來執行HTTP連接?這是很好的練習,但它需要深入瞭解HTTP協議的內部知識。爲什麼不只是使用類URL和URLConnection?

BufferedReader dIn = new BufferedReader(new URL("http://127.0.0.1:80").openConnection().getInputStream()); 
do { 
     str = dIn.readLine(); 
     System.out.println(str); 
    } while (str != null); 
} 
+0

嘿,這很好,但我想用插座,因爲它是我的任務 – codeomnitrix 2010-12-01 14:00:16