2010-04-03 60 views
22

我在Android手機上有此代碼。如何打印出HttpResponse返回的消息?

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

我有了在頁面加載此

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

我想抓住從HttpReponse這個響應,並打印出來一個asp.net Web窗體應用程序。我該怎麼做呢?

我試過response.getEntity().toString()但它似乎打印出內存中的地址。

感謝

回答

38

使用ResponseHandler。一行代碼。有關使用它的示例Android項目,請參閱herehere。這個帖子的

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 
    } 
} 

附加組合和完整的HttpClient在 - http://www.androidsnippets.org/snippets/36/

+0

的Android API版本,這是否成爲可在?我可能不得不重寫來自代碼:D – 2010-04-04 00:26:15

+0

我認爲它從一開始就一直存在,或者至少從Android 0.9開始。它是標準HttpClient 4.x軟件包的一部分。 – CommonsWare 2010-04-04 00:32:30

8

我只想做舊的方式。如果您在響應中獲得不同的內容類型,它比ResponseHandler更具防彈性。

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

此代碼將在響應返回整個響應消息作爲String,和狀態碼在RSP,作爲int

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

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

我用下面的代碼

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();