entity.getContentLength()返回-1

时间:2014-02-18 04:50:22

标签: android android-parser android-json httpentity

我得到BufferedReader对象是空白的,当我调试我的代码时,我发现实际上HttpEntity对象似乎也是空的。

以下是我的代码部分:

//发出HTTP请求

try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Accept", "JSON");

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            long len = httpEntity.getContentLength();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (UnknownHostException e){
            e.getMessage();
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

如果我在PC浏览器上点击我的网址,它会给出JSON响应,也会在[http://jsonlint.com/] [1]

究竟是什么问题,我无法理解

1 个答案:

答案 0 :(得分:0)

检查响应状态,然后开始阅读响应

 HttpResponse httpResponse = httpClient.execute(httpPost);
 if(httpResponse .getStatusLine().getStatusCode() == SC_OK)
 {
   HttpEntity httpEntity = httpResponse.getEntity();
   long len = httpEntity.getContentLength();
   is = httpEntity.getContent();
  }