URLjava.io.IOException:服务器在JAVA中返回HTTP响应代码:411

Ara*_*asu 8 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();
Run Code Online (Sandbox Code Playgroud)

在运行此代码时,我得到了例外

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

可能是什么错误.

Jon*_*eet 6

HTTP状态代码411表示"需要长度" - 您尝试发出POST请求,但您从未提供任何输入数据.Java客户端代码未设置Content-Length标头,并且服务器拒绝没有长度的POST请求.

为什么你甚至试图发帖?为什么不提出GET请求,或者更好的是HEAD?

我还建议,如果您真的需要知道某个特定网站是否已启动(例如,网络服务),您是否已连接到该网站,而不仅仅是Google.


nIc*_*cOw 5

尝试在代码中添加以下行,这可能有助于您更好地理解问题:

 conn.setRequestProperty("Content-Length", "0");
Run Code Online (Sandbox Code Playgroud)

通过添加以下代码来检查HTTP ERROR 411中的 inputStream是什么状态:

InputStream is = null;
if (conn.getResponseCode() != 200) 
{
    is = conn.getErrorStream();
} 
else 
{
    is = conn.getInputStream();
}
Run Code Online (Sandbox Code Playgroud)

希望这可能会有所帮助.

问候