如何打印出来自HttpResponse返回的消息?

2022-09-01 13:44:01

我的安卓手机上有这个代码。

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

我有一个 asp.net Web表单应用程序,该应用程序在页面中加载了这个

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

我想从HttpReponse中获取此响应并将其打印出来。我该怎么做?

我试过了,但它似乎只是打印出内存中的地址。response.getEntity().toString()

谢谢


答案 1

使用响应处理程序。一行代码。请参阅此处此处,了解使用它的示例 Android 项目。

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 at - http://www.androidsnippets.org/snippets/36/


答案 2

我会用旧的方式去做。它比RecertHandler更防弹,以防您在响应中获得不同的内容类型。

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

推荐