2010-12-05 201 views
5

我使用這個代碼張貼到HTTP服務器的請求:閱讀HttpPost響應

HttpClient client = new DefaultHttpClient(); 
HttpPost post = new HttpPost("http://192.168.0.1/test.php"); 
HttpResponse response = null; 
try { 
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
    nameValuePairs.add(new BasicNameValuePair("num", "2")); 
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
    response = client.execute(post); 
} 
catch(ClientProtocolException e) { 
    ... 
} 
catch(IOException e) { 
    ... 
} 

的反應只不過是一個簡單的String更多。我怎樣才能將這個答案讀作String?它似乎不像HttpResponse有直接做這個的方法。

回答

10

我已經創建了Android中的POST方法發送數據和特殊的頭(頭HashMap的可能是空的,如果你沒有任何自定義頁眉)這個helper方法:

public static String getStringContent(String uri, String postData, 
     HashMap<String, String> headers) throws Exception { 

     HttpClient client = new DefaultHttpClient(); 
     HttpPost request = new HttpPost(); 
     request.setURI(new URI(uri)); 
     request.setEntity(new StringEntity(postData)); 
     for(Entry<String, String> s : headers.entrySet()) 
     { 
      request.setHeader(s.getKey(), s.getValue()); 
     } 
     HttpResponse response = client.execute(request); 

     InputStream ips = response.getEntity().getContent(); 
     BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8")); 
     if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK) 
     { 
      throw new Exception(response.getStatusLine().getReasonPhrase()); 
     } 
     StringBuilder sb = new StringBuilder(); 
     String s; 
     while(true) 
     { 
      s = buf.readLine(); 
      if(s==null || s.length()==0) 
       break; 
      sb.append(s); 

     } 
     buf.close(); 
     ips.close(); 
     return sb.toString(); 

} 
+1

恕我直言,這是更好地檢查,如果情況確定第一,如果(response.getStatusLine()。getStatusCode()== HttpStatus.SC_OK){//一些代碼}其他{//一些處理..} – 2011-11-15 13:31:59

5

response.getStatusLine(); //用於讀狀態線

org.apache.http.util.EntityUtils.toString(response.getEntity());