2013-06-20 58 views
0

我正在使用Ubuntu 12.04。這是使用URLConnection實現HTTP GET方法的簡單代碼。使用URLConnection的HTTP GET請求無法訪問任何頁面

import java.io.BufferedReader; 
import java.io.DataOutputStream; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.URL; 

import javax.net.ssl.HttpsURLConnection; 

public class HttpURLConnectionExample { 

private final String USER_AGENT = "Mozilla/5.0"; 

public static void main(String[] args) throws Exception { 

    HttpURLConnectionExample http = new HttpURLConnectionExample(); 

    System.out.println("Testing 1 - Send Http GET request"); 
    http.sendGet(); 
} 

// HTTP GET request 
private void sendGet() throws Exception { 

    String url = "https://www.google.com/search?q=flower"; 

    URL obj = new URL(url); 
    HttpURLConnection con = (HttpURLConnection) obj.openConnection(); 

    // optional default is GET 
    con.setRequestMethod("GET"); 

    //add request header 
    con.setRequestProperty("User-Agent", USER_AGENT); 

    int responseCode = con.getResponseCode(); 
    System.out.println("\nSending 'GET' request to URL : " + url); 
    System.out.println("Response Code : " + responseCode); 

    BufferedReader in = new BufferedReader(
      new InputStreamReader(con.getInputStream())); 
    String inputLine; 
    StringBuffer response = new StringBuffer(); 

    while ((inputLine = in.readLine()) != null) { 
     response.append(inputLine); 
    } 
    in.close(); 

    //print result 
    System.out.println(response.toString()); 

    } 

} 

但是當我編譯並運行Ubuntu的終端這段代碼,這段代碼的輸出不產生由URL指定的頁面的內容。相反,它給出以下輸出

Testing 1 - Send Http GET request 

Sending 'GET' request to URL : http://www.google.com/search?q=flower 
Response Code : 307 
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>307 Temporary Redirect</title></head><body><h1>Temporary Redirect</h1><p>The document has moved <a href="https://ifwb.iitb.ac.in/index.php?add=www.google.com/search">here</a>.</p><hr><address>Apache/2.2.22 (Fedora) Server at www.google.com Port 80</address></body></html> 

此問題適用於我在代碼中指定的任何URL。此外,我嘗試使用Telnet客戶端來訪問網絡內容,如

遠程登錄www.google.com 80 GET/

,並讓不僅爲www.google.com但對於類似的結果每個網址。 我是IIT Bombay的學生,可能與https://ifwb.iitb.ac.in有關。 我也想堅持java.net而不是apache httpclient。所以幫我解決這個問題。

回答

0

看來你被服務器拒絕,因爲不完整的請求。使用任何嗅探器(如Fiddler或Wireshark)「學習示例」是一個不錯的主意:比較您的請求和來自特定軟件(如瀏覽器)的請求。

下面是Wireshark dump的摘錄,IE10如何向感興趣的URL發送GET請求。正如您所看到的,描述客戶端功能和期望的各個領域都是如此,所以查詢的服務器可以以最合適和易用的形式返回答案。與谷歌/ RFC請教看到經過的每個參數的含義:

GET /搜Q =花HTTP/1.1

接受:text/html的,是application/xhtml + xml的,/

接受語言:EN-US

的User-Agent:Mozilla的/ 5.0(兼容; MSIE 10.0; Windows NT的6.1; WOW64; 三叉戟/ 6.0)

接受編碼:gzip,緊縮

主持人:www.google.com

DNT:1個

連接:保持活動

的Cookie:一些民營這裏說明]