28

我的 Android 手机上有此代码。

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

我有一个在页面中加载的 asp.net webform 应用程序

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

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

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

谢谢

4

5 回答 5

40

使用ResponseHandler. 一行代码。有关使用它的示例 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
    }
} 

在 - http://www.androidsnippets.org/snippets/36/添加这篇文章和完整的 HttpClient 的组合

于 2010-04-04T00:12:00.530 回答
12

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

ByteArrayOutputStream outstream = new ByteArrayOutputStream();
response.getEntity().writeTo(outstream);
byte [] responseBody = outstream.toByteArray();
于 2010-04-07T16:19:58.273 回答
8

我使用了以下代码

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();
于 2013-01-03T08:31:45.423 回答
7

最简单的方法可能是使用org.apache.http.util.EntityUtils

String message = EntityUtils.toString(response.getEntity());

它读取实体的内容并将其作为字符串返回。使用来自实体的字符集(如果有)转换内容,否则使用“ISO-8859-1”。

如有必要,您可以显式传递默认字符集 - 例如

String message = EntityUtils.toString(response.getEntity(). "UTF-8");

如果在实体中找不到,则使用提供的默认字符集将实体内容作为字符串获取。如果传递的默认字符集为空,则使用默认的“ISO-8859-1”。

于 2018-09-18T08:09:43.187 回答
5

此代码将在 response 中以 a 形式返回整个响应消息,并在rsp中以 a 形式返回String状态代码。int

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

rsp = response.getStatusLine().getStatusCode();`
于 2012-12-28T07:52:36.910 回答