2014-02-18 84 views
0

我得到BufferedReader對象是空的,當我調試我的代碼時,我發現實際上HttpEntity對象似乎也是空的。entity.getContentLength()返回-1

這裏是我的部分代碼:

//製作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上的瀏覽器的URL,它提供了一個JSON響應,還取決於[HTTP: //jsonlint.com/][1]

什麼是確切的問題,我無法理解

+0

此代碼在asyntask或線程中。? –

+1

什麼是HTTP響應狀態?你爲什麼沒有[使用'BasicResponseHandler'將響應轉換爲字符串](http://stackoverflow.com/a/2573112/139010)? –

+0

@wqrahd是的,這是進入a​​syns任務 – Rohit

回答

0

檢查響應狀態,然後開始讀取響應

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

我得到的狀態碼是200,但仍然是entity.getContentLength()是-1 – Rohit