2010-04-03 12 views
22

Tôi có mã này trên điện thoại Android của mình.Làm thế nào để in ra thư trả về từ HttpResponse?

URI uri = new URI(url); 
    HttpPost post = new HttpPost(uri); 
    HttpClient client = new DefaultHttpClient(); 
    HttpResponse response = client.execute(post); 

Tôi có một ứng dụng Webform asp.net có trong tải trang này

Response.Output.Write("It worked"); 

Tôi muốn lấy đáp ứng này từ HttpReponse và in nó ra. Làm thế nào để tôi làm điều này?

Tôi đã thử response.getEntity().toString() nhưng dường như chỉ in ra địa chỉ trong bộ nhớ.

Cảm ơn

Trả lời

38

Sử dụng ResponseHandler. Một dòng mã. Xem herehere cho các dự án Android mẫu sử dụng nó.

public void postData() { 
    // Create a new HttpClient and Post Header 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("http://www.yoursite.com/user"); 

    try { 
     // Add your data 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
     nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
     nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!")); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

     // Execute HTTP Post Request 
     ResponseHandler<String> responseHandler=new BasicResponseHandler(); 
     String responseBody = httpclient.execute(httppost, responseHandler); 
     JSONObject response=new JSONObject(responseBody); 
    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
    } 
} 

add kết hợp của bài này và hoàn thành HttpClient tại - http://www.androidsnippets.org/snippets/36/

+0

mà android api phiên bản thực hiện điều này trở nên có sẵn tại? Tôi có thể phải viết lại mã: D –

+0

Tôi nghĩ rằng nó đã có từ đầu, hoặc ít nhất là từ Android 0.9. Đó là một phần của gói HttpClient 4.x tiêu chuẩn. – CommonsWare

8

tôi sẽ chỉ làm điều đó theo cách cũ. Nó có khả năng chống đạn hơn ResponseHandler, trong trường hợp bạn nhận được các kiểu nội dung khác nhau trong phản hồi.

ByteArrayOutputStream outstream = new ByteArrayOutputStream(); 
response.getEntity().writeTo(outstream); 
byte [] responseBody = outstream.toByteArray(); 
3

Mã này sẽ trả lại toàn bộ thông điệp phản ứng trong đáp ứng như một String, và mã trạng thái trong RSP, như là một int.

respond = response.getStatusLine().getReasonPhrase(); 

rsp = response.getStatusLine().getStatusCode();` 
6

tôi đã sử dụng đoạn mã sau

BufferedReader r = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 

StringBuilder total = new StringBuilder(); 

String line = null; 

while ((line = r.readLine()) != null) { 
    total.append(line); 
} 
r.close(); 
return total.toString(); 
Các vấn đề liên quan