如何从响应标题中获取内容长度?

时间:2014-05-24 09:36:01

标签: java android httpconnection

我正在使用此代码使用AsyncTask从网址获取数据:

 protected String doInBackground(Object... params) {
    int ResponseCode=-1;
    try {
        URL myURL=new URL("URL...");
        HttpURLConnection connection=(HttpURLConnection) myURL.openConnection();
        connection.connect();
        ResponseCode=connection.getResponseCode();

        if (ResponseCode==HttpURLConnection.HTTP_OK) {
            InputStream inputStream=connection.getInputStream();
            Reader reader=new InputStreamReader(inputStream);
            int contentLength=connection.getContentLength();
            char[] charArray=new char[contentLength];
            reader.read(charArray);
            String responseData=new String(charArray);
            Log.i("TAG", responseData);
            Log.i("TAG", ""+contentLength);
        }
        else {
            Log.i("TAG", " Unsuccessful HTTP Response Code: "+ResponseCode);
        }

    }catch (MalformedURLException e) {
            Log.i("TAG", "MalformedURLException Error: "+e.getMessage());
    } catch (IOException e) {
            Log.i("TAG", "IOException Error: "+e.getMessage());
    } catch (Exception e) {
            Log.i("TAG", "Exception Error: "+e);
    }
    return " "+ResponseCode;
}

上面的代码工作正常,我在一些项目中使用它,但对于我正在处理的URL,它不起作用,并且总是为Response Codebecause the HTTP response of my URL doesn't contain Content-Length header, the content is chunked.返回-1,现在我想知道有没有相同的方法呢? 先谢谢

2 个答案:

答案 0 :(得分:0)

遵循http规范,如果内容类型被分块,则可以在标题" Transfer-Encoding"之后在流上读取内容长度。它看起来像这样:

HTTP/1.1 200 OK
Date: Fri, 23 May 2014 21:17:12 GMT
Content-Type: text/plain
Transfer-Encoding: chunked

5F

这里" 5F"是从该点开始的http响应的十六进制长度(在这种情况下为95字节)。

请注意,在标题之后和长度之前有一个换行符。

欲了解更多信息:

简单解释http协议:http://www.jmarshall.com/easy/http/#http1.1c2 RFC(官方的,完整的):http://tools.ietf.org/html/rfc2616

答案 1 :(得分:0)

最后我以这种方式解决了我的问题:

try {
     URL blogPostURL=new URL("URL...");
     URLConnection connection=blogPostURL.openConnection();
     BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
     String responseData;
     while ((responseData = reader.readLine()) != null){ 
             Log.i("TAG", responseData);
     }
     reader.close();
}catch (MalformedURLException e) {
     Log.i("TAG", "MalformedURLException Error: "+e.getMessage());
} catch (IOException e) {
     Log.i("TAG", "IOException Error: "+e.getMessage());
} catch (Exception e) {
     Log.i("TAG", "Exception Error: "+e);
}