2012-01-04 156 views
7

我檢查網絡是否可用與否URLjava.io.IOException:服務器返回的HTTP響應代碼:411 JAVA

URL url = new URL("http://www.google.co.in/"); 
      final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 

      // set connect timeout. 
      conn.setConnectTimeout(1000000); 

      // set read timeout. 
      conn.setReadTimeout(1000000); 

      conn.setRequestMethod("POST"); 

      conn.setRequestProperty("Content-Type","text/xml"); 

      conn.setDoOutput(true); 

      conn.connect(); 

      Integer code = conn.getResponseCode(); 
      final String contentType = conn.getContentType(); 

雖然運行此代碼,我發現了異常

URLjava.io.IOException: Server returned HTTP response code: 411

什麼可能是錯誤。

+0

[Might help](http://www.checkupdown.com/status/E411.html) – 2012-01-04 06:28:31

回答

6

HTTP狀態代碼411名的意思是「長度所需」 - 你試圖讓一個POST請求,但是你從來沒有提供的任何輸入數據。 Java客戶端代碼不設置Content-Length標頭,服務器拒絕沒有長度的POST請求。

爲什麼你甚至試圖發表一篇文章呢?爲什麼不提出GET請求,或者更好的是HEAD?

我還建議,如果您確實需要知道某個特定網站是否已啓動(例如,網絡服務),那麼您將連接到該網站,而不僅僅是Google。

+0

我設置了conn.setRequestProperty(「Content-Length」,「500000」);仍然有相同的錯誤發生 – Arasu 2012-01-04 06:56:54

+1

@Arasu:但你仍然沒有設置任何數據 - 所以我不會感到驚訝,如果客戶端代碼刪除Content-Length頭。再次,*爲什麼*您是否在嘗試發出POST請求? – 2012-01-04 06:59:29

+0

客戶端網址應該只運行一次,因爲它會計入交易。有時客戶端互聯網可能會下降我們的可能不會因此,只有當我們的互聯網啓動時,我們才能連接到客戶端。 – Arasu 2012-01-04 07:04:25

2

411 - 長度必

當服務器拒絕,因爲沒有指定內容長度被處理請求時發生411狀態代碼。

參考for details

5

嘗試以下行添加到您的代碼,可以幫助你理解這個問題好一點:

conn.setRequestProperty("Content-Length", "0"); 

通過將此代碼做檢查你的的inputStream從HTTP錯誤411種狀態:

InputStream is = null; 
if (conn.getResponseCode() != 200) 
{ 
    is = conn.getErrorStream(); 
} 
else 
{ 
    is = conn.getInputStream(); 
} 

希望這可能有所幫助。

問候

2

添加在執行職務的下面一行代碼工作:修改或創建在後端的新實例時

conn.setRequestProperty("Content-Length", "0"); 
0

POST/PUT應該使用。 當以http:///// {parameter1}/{parameter2}(等等)的形式使用REST調用時,不會發送查詢或主體!如果修改數據,它仍然應該是POST調用。

所以,在這種情況下,我們可以做一些反思。

String urlParameters = url.getQuery(); 
if (urlParameters == null) urlParameters = ""; 

byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); 
int postDataLength = postData.length; 
if (postDataLength > 0) { 
//in case that the content is not empty 
     conn.setRequestProperty("Content-Length", Integer.toString(postDataLength)); 
    } else { 
     // Reflaction the HttpURLConnectioninstance 
     Class<?> conRef = conn.getClass(); 
     // Fetch the [requests] field, Type of MessageHeader 
     Field requestsField= conRef .getDeclaredField("requests"); 
     // The [requests] field is private, so we need to allow accessibility 
     requestsField.setAccessible(true); 
     MessageHeader messageHeader = (MessageHeader) requestsField.get(conn); 
     // Place the "Content-Length" header with "0" value 
     messageHeader.add("Content-Length", "0"); 
     // Inject the modified headers 
     requestsField.set(conn, messageHeader); 
    } 

通過這種方式,我們不會損害現有的模型,並且將使用零長度標頭髮送呼叫。

相關問題