HTTP 411 ERROR CODE的处理方法

来源:互联网 发布:3g网络和2g网络的区别 编辑:程序博客网 时间:2024/06/08 01:30

在JAVA程序请求远程的URL时,有时候会得到如下的错误信息:

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

这是因为采用HTTP POST的方法向Web服务器请求时,没有提供相应的BODY数据,有的Web服务器就会拒绝这样的请求。我们可以参看错误代码411的官方解释(http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html):

10.4.12 411 Length Required

The server refuses to accept the request without a defined Content- Length. The client MAY repeat the request if it adds a valid Content-Length header field containing the length of the message-body in the request message.

解决方法是在请求头中设置一个Content-Length=0,并且向outputstream中写入一个空的BODY数据。

        URL url = new URL("http://www.webservicex.net/MortgageIndex.asmx/GetCurrentMortgageIndexByWeekly");
        
        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");

        conn.setRequestProperty("Content-Type","text/xml");
        
        conn.setRequestProperty("Content-Length","0");
        DataOutputStream os = new DataOutputStream( conn.getOutputStream() );
        os.write( "".getBytes("UTF-8"), 0, 0);
        os.flush();
        os.close();
        
        conn.connect();
        
        InputStream is = conn.getInputStream();

        Integer code = conn.getResponseCode();
        final String contentType = conn.getContentType();
        System.out.println(code+":"+contentType);