2012-07-30 188 views
5

我正在嘗試使用HTTPUrlConnection獲取URL,但是我總是收到500代碼,但是當我嘗試從瀏覽器訪問相同的URL或使用curl時,它工作正常!Java HTTPUrlConnection返回500狀態代碼

這是代碼

try{ 
    URL url = new URL("theurl"); 
    HttpURLConnection httpcon = (HttpURLConnection) url.openConnection(); 
    httpcon.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); 
    httpcon.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:14.0) Gecko/20100101 Firefox/14.0.1"); 
    System.out.println(httpcon.getHeaderFields()); 
    }catch (Exception e) { 
     System.out.println("exception "+e); 
    } 

當我打印headerfields,它顯示了500碼。當我更改URL別的東西如google.com,它工作正常。但我不明白爲什麼它不起作用,但它在瀏覽器和curl上正常工作。

任何幫助將高度讚賞..

謝謝

+0

來修復它是用於內部服務器錯誤 – 2012-07-30 12:50:23

+0

你試過了什麼'theurl'? – sunil 2012-07-30 13:15:11

+0

@sunil我正在嘗試http://www.rassd.com/1-23544.htm – user1069624 2012-07-30 13:31:13

回答

1

確保您的連接允許以下重定向 - 這是您的連接和瀏覽器之間行爲不同的可能原因之一(默認情況下允許重定向)。

它應該返回代碼3xx,但可能有其他地方將其更改爲500爲您的連接。

+0

emm ..我不認爲這是問題,因爲我沒有重定向時我在瀏覽器中嘗試它..但感謝提示。 – user1069624 2012-07-30 13:32:27

+0

按照Muse的建議從錯誤流中讀取更多錯誤細節。如果它不是重定向而不是唯一的其他可能性,我可以想到的是服務器在你的請求中需要其他的東西(cookie,其他類型的頭文件)。我會複製成功的請求中的瀏覽器傳遞的所有頭文件(它應該會導致成功的HttpURLConnection調用),而不是按照我的方式一次刪除一個頭文件。 – 2012-07-30 13:40:30

+0

好吧,我想我知道什麼是錯的。頁面實際上是關閉的,但是從瀏覽器我認爲它用來獲得緩存版本..可以這樣嗎?因爲該頁面不工作..但是當我嘗試在同一主機下的另一個頁面..它的工作原理! – user1069624 2012-07-30 14:47:44

7

這主要是因爲編碼而發生的。 如果您使用的瀏覽器正常,但在您的程序中收到500(內部服務器錯誤),這是因爲瀏覽器具有關於字符集和內容類型的高度複雜的代碼。

這裏是我的代碼,它適用於ISO8859_1作爲字符集和英語的情況。

public void sendPost(String Url, String params) throws Exception { 


    String url=Url; 
    URL obj = new URL(url); 
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); 

    con.setRequestProperty("Acceptcharset", "en-us"); 
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); 
    con.setRequestProperty("charset", "EN-US"); 
    con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); 
    String urlParameters=params; 
    // Send post request 
    con.setDoOutput(true); 
    con.setDoInput(true); 
    con.connect(); 
    //con. 

    DataOutputStream wr = new DataOutputStream(con.getOutputStream()); 
    wr.writeBytes(urlParameters); 
    wr.flush(); 
    wr.close(); 

    int responseCode = con.getResponseCode(); 
    System.out.println("\nSending 'POST' request to URL : " + url); 
    System.out.println("Post parameters : " + urlParameters); 
    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()); 
    this.response=response.toString(); 
    con.disconnect(); 

} 

,並在主程序中,這樣稱呼它:

myclassname.sendPost("https://change.this2webaddress.desphilboy.com/websitealias/orwebpath/someaction","paramname="+URLEncoder.encode(urlparam,"ISO8859_1")) 
2

我跑進「網址在瀏覽器的工作原理的問題,但是當我做HTTP-GET在Java中,我得到一個500錯誤」。

在我的情況下,問題是,普通HTTP-GET在/default.aspx之間的無限重定向循環結束了和/login.aspx

 URL oUrl = new URL(url); 
     HttpURLConnection con = (HttpURLConnection) oUrl.openConnection(); 
     con.setRequestMethod("GET"); 
     ... 
     int responseCode = con.getResponseCode(); 

發生了什麼事是:服務器提供了一個三部分cookie和con.getResponseCode()僅使用其中一個部分。標題中的Cookie數據是這樣的:

header.key = null 
    value = HTTP/1.1 302 Found 
... 
header.key = Location 
    value = /default.aspx 
header.key = Set-Cookie 
    value = WebCom-lbal=qxmgueUmKZvx8zjxPftC/bHT/g/rUrJXyOoX3YKnYJxEHwILnR13ojZmkkocFI7ZzU0aX9pVtJ93yNg=; path=/ 
    value = USE_RESPONSIVE_GUI=1; expires=Wed, 17-Apr-2115 18:22:11 GMT; path=/ 
    value = ASP.NET_SessionId=bf0bxkfawdwfr10ipmvviq3d; path=/; HttpOnly 
... 

所以僅接收所需的數據糊塗了三分之一當服務器:你登錄!無需等待,您必須登錄。不,您已登錄,...

要解決無限重定向循環,我必須手動查找重定向並手動解析「Set-cookie」條目的標題。

  con = (HttpURLConnection) oUrl.openConnection(); 
      con.setRequestMethod("GET"); 
      ... 
      log.debug("Disable auto-redirect. We have to look at each redirect manually"); 
      con.setInstanceFollowRedirects(false); 
      .... 
      int responseCode = con.getResponseCode(); 

有了這個代碼中的Cookie的分析,如果我們在responseCode重定向:

private String getNewCookiesIfAny(String origCookies, HttpURLConnection con) { 
    String result = null; 
    String key; 
    Set<Map.Entry<String, List<String>>> allHeaders = con.getHeaderFields().entrySet(); 
    for (Map.Entry<String, List<String>> header : allHeaders) { 
     key = header.getKey(); 

     if (key != null && key.equalsIgnoreCase(HttpHeaders.SET_COOKIE)) { 
      // get the cookie if need, for login 
      List<String> values = header.getValue(); 
      for (String value : values) { 
       if (result == null || result.isEmpty()) { 
        result = value; 
       } else { 
        result = result + "; " + value; 
       } 
      } 
     } 
    } 
    if (result == null) { 
     log.debug("Reuse the original cookie"); 
     result = origCookies; 
    } 
    return result; 
} 
0

在我的情況下,它變成了服務器總是返回HTTP/1.1 500(在瀏覽器如在Java中)我想訪問的頁面,但成功地提供了網頁內容。

通過瀏覽器訪問特定頁面的人只是沒有注意到,因爲他會看到頁面,沒有錯誤信息,在Java中,我必須讀取錯誤流而不是輸入流(謝謝@Muse)。

雖然我不知道爲什麼。可能會讓一些爬行者不知所措。

0

這是一個老問題,但我有同樣的問題,並通過這種方式解決它。

這可能有助於其他情況一樣。

在我的情況下,我正在開發本地環境系統,當我從瀏覽器中檢查了我的Rest Api時,每件事情都很好,但我一直在我的Android系統中拋出HTTP錯誤500。

問題是,當您使用Android時,它在VM(虛擬機)上工作,表示您的本地計算機防火牆可能會阻止您的虛擬機訪問本地URL(IP)地址。

你只需要在你的電腦防火牆中允許。如果您嘗試從網絡外部訪問系統,則同樣適用。

0

我面臨同樣的問題,我們的問題是其中一個參數值中有一個特殊的符號。我們通過使用URLEncoder.encode(String, String)

相關問題