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

cho*_*bo2 25 .net java android httpresponse

我在Android手机上有这个代码.

   URI uri = new URI(url);
   HttpPost post = new HttpPost(uri);
   HttpClient client = new DefaultHttpClient();
   HttpResponse response = client.execute(post);
Run Code Online (Sandbox Code Playgroud)

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

 Response.Output.Write("It worked");
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢

Com*_*are 38

使用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
    }
} 
Run Code Online (Sandbox Code Playgroud)

添加此帖子的组合并完成HttpClient - http://www.androidsnippets.org/snippets/36/


hnv*_*iet 10

我会以旧的方式做到这一点.如果您在响应中获得不同的内容类型,它比ResponseHandler更具防弹性.

ByteArrayOutputStream outstream = new ByteArrayOutputStream();
response.getEntity().writeTo(outstream);
byte [] responseBody = outstream.toByteArray();
Run Code Online (Sandbox Code Playgroud)


Jim*_*Loe 7

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

String message = EntityUtils.toString(response.getEntity());
Run Code Online (Sandbox Code Playgroud)

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

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

String message = EntityUtils.toString(response.getEntity(). "UTF-8");
Run Code Online (Sandbox Code Playgroud)

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


Lun*_*unf 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();
Run Code Online (Sandbox Code Playgroud)


San*_*ita 5

此代码将在返回整个响应消息响应一个String,和状态码在RSP,作为一个int

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

rsp = response.getStatusLine().getStatusCode();`
Run Code Online (Sandbox Code Playgroud)