从 HttpResponse 中提取消息正文

发布于 2024-11-28 01:40:10 字数 117 浏览 1 评论 0原文

好的,我已成功连接到远程服务器并收到 HTTP/1.1 200 OK 响应,并且该响应被打包到 HttpResponse 对象中。现在我如何从中获取响应中的数据,特别是从服务器发送的 JSON?

Okay, I've successfully connected to a remote server and received a HTTP/1.1 200 OK response and the response is packed into the HttpResponse object. Now how do I get the data in the response out of it, specifically the JSON that was sent from the server?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

秋风の叶未落 2024-12-05 01:40:10

像这样的东西:这里重复: How do I parse JSON from Java HTTPResponse?

HttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONTokener tokener = new JSONTokener(json);
JSONArray finalResult = new JSONArray(tokener);

something like this: duplicate here : How do I parse JSON from a Java HTTPResponse?

HttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONTokener tokener = new JSONTokener(json);
JSONArray finalResult = new JSONArray(tokener);
十秒萌定你 2024-12-05 01:40:10

那么,您可以通过调用返回 HttpEntity 类型的对象的 getEntity() 来获取 HttpResponse 的正文。然后,您将需要使用从 HttpEntitygetContent() 方法返回的 InputStream。我会这样做:

public static String entityToString(HttpEntity entity) {
  InputStream is = entity.getContent();
  BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
  StringBuilder str = new StringBuilder();

  String line = null;
  try {
    while ((line = bufferedReader.readLine()) != null) {
      str.append(line + "\n");
    }
  } catch (IOException e) {
    throw new RuntimeException(e);
  } finally {
    try {
      is.close();
    } catch (IOException e) {
      //tough luck...
    }
  }
  return str.toString();
}

Well, you can get the body of the HttpResponse by calling getEntity() which returns an object of type HttpEntity. You will then want to consume the InputStream that is returned from the getContent() method of the HttpEntity. I would do it like this:

public static String entityToString(HttpEntity entity) {
  InputStream is = entity.getContent();
  BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
  StringBuilder str = new StringBuilder();

  String line = null;
  try {
    while ((line = bufferedReader.readLine()) != null) {
      str.append(line + "\n");
    }
  } catch (IOException e) {
    throw new RuntimeException(e);
  } finally {
    try {
      is.close();
    } catch (IOException e) {
      //tough luck...
    }
  }
  return str.toString();
}
任性一次 2024-12-05 01:40:10

您还可以使用 EntityUtils

response = cl.execute(p); //cl is http client and p is the post request

if(response.getStatusLine().getStatusCode()==200)
{
    try
    {
        String resp_body = EntityUtils.toString(response.getEntity());
        Log.v("resp_body", resp_body.toString());
        JSONObject jsobj = new JSONObject(resp_body);
    }
    catch(Exception e)
    {

       Log.e("sometag",e.getMessage());
     }
}

PS:您可能必须在主线程之外的单独线程中执行此操作,例如在 AsyncTask 的 doInBackground() 中,或者主线程上的网络操作可能会发生异常。

You may also use EntityUtils

response = cl.execute(p); //cl is http client and p is the post request

if(response.getStatusLine().getStatusCode()==200)
{
    try
    {
        String resp_body = EntityUtils.toString(response.getEntity());
        Log.v("resp_body", resp_body.toString());
        JSONObject jsobj = new JSONObject(resp_body);
    }
    catch(Exception e)
    {

       Log.e("sometag",e.getMessage());
     }
}

PS : You may have to do this in a separate thread, other than the main thread, like in the doInBackground() of an AsyncTask or Network operation on main thread exception may occur.

凡尘雨 2024-12-05 01:40:10

调用 httpclient.execute() 时使用 BasicResponseHandler

ResponseHandler <String> resonseHandler = new BasicResponseHandler();
String response = httpclient.execute(httpget, resonseHandler);

Use a BasicResponseHandler when calling httpclient.execute()

ResponseHandler <String> resonseHandler = new BasicResponseHandler();
String response = httpclient.execute(httpget, resonseHandler);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文