2012-01-04 158 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); 
    } 

通过这种方式,我们不会损害现有的模型,并且将使用零长度标头发送呼叫。

相关问题