【问题标题】:How to read the response from the HTTPClient如何从 HTTPClient 读取响应
【发布时间】:2011-12-01 16:11:55
【问题描述】:

我正在围绕 HTTPClient 发送 POST 请求并获得响应。我得到的响应代码是好的。

我想从该回复HttpEntity entity =response.getEntity(); 中读取一些内容 我正在控制台System.out.println(EntityUtils.toString(entity)); 上打印该响应。

它正在打印{"created_at":"2011-12-01T07:56:50+00:00","type":"sample","id":29,"status":"received"}

我想从上面的字符串中读取id,。

任何人都可以帮助如何从实体中检索 id。

提前谢谢..

【问题讨论】:

    标签: java httpclient


    【解决方案1】:

    数据是JSON数据。

    你可以去json.org下载JSONObject

    你可以这样做,

    JSONObject json = new JSONObject(EntityUtils.toString(entity));
    int id = json.getInt("id");
    

    【讨论】:

    • 嗨,精英,我正在使用net.sf.json.JSONObject,它在JSONObject json = new JSONObject(EntityUtils.toString(entity)); 行给出的编译错误 String 构造函数未定义。
    • 在这个例子中我没有使用net.sf.json.JSONObject,而是org.json.JSONObject
    • 可以,直接从Github的下载link下载代码。我下载了 ZIP 文件。
    • 我收到Attempted read from closed stream. 异常。我没有在这里使用任何流
    • 你必须为这个新问题打开一个新的 SO 问题。
    【解决方案2】:

    您的响应似乎是 JSON 之一。可以使用 JSON 库吗,例如 Jackson

    【讨论】:

      【解决方案3】:

      这种方法效率不高,但你也可以试试。

      BufferedReader  br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
              String readLine;
              while(((readLine = br.readLine()) != null)) {
                System.err.println(readLine);
            }
      
      if(readLine.indexOf(",") > -1 && readLine.indexOf(":") > -1)
      String id = (readLine.split(",")[2]).split(":")[1];
      

      【讨论】:

        猜你喜欢
        • 2013-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-31
        • 1970-01-01
        • 2019-10-24
        • 1970-01-01
        • 2021-01-18
        相关资源
        最近更新 更多