【问题标题】:How to get raw JSON text from Unirest response in Java如何从 Java 中的 Unirest 响应中获取原始 JSON 文本
【发布时间】:2019-05-14 01:30:35
【问题描述】:

我正在尝试向服务器发送 POST 请求,获取响应并解析它(它是一个 JSON 文件)。

我正在使用 Unirest 进行 POST 请求,如下所示:

        HttpResponse<JsonNode> response = Unirest
                .post("http://myserver.com/file")
                  .header("cache-control", "no-cache")
                  .header("Postman-Token", "02ec2fa1-afdf-4a2a-a535-353424d99400")
                .header("Content-Type", "application/json")
                .body("{some JSON body}")
                .asJson();

        // retrieve the parsed JSONObject from the response
        JSONObject myObj = response.getBody().getObject();
        // extract fields from the object
        String msg = myObj.toString();

        System.out.println(msg);

但我在获取原始 JSON 文本时遇到问题(我想使用 JSONPath 来解析响应)。

我该怎么做?到目前为止,我调用toString() 方法的所有尝试都失败了。

【问题讨论】:

    标签: java json jsonpath unirest jsonparser


    【解决方案1】:

    你可以这样做:

    InputStream inputStream = response.getRawBody();
    BufferedInputStream bis = new BufferedInputStream(inputStream);
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    int result = bis.read();
    while(result != -1) {
        buf.write((byte) result);
        result = bis.read();
    }
    
    String rawJson = buf.toString("UTF-8");
    

    【讨论】:

    • 是的,但这不会返回字符串。是InputStream
    • 您可以将输入流读入字符串。您可以查看stackoverflow.com/questions/309424/…
    • 是的,我知道。但是考虑是否有更简单的方法可以做到这一点(顺便说一句,请发布完整答案,以便我将您标记为最佳答案)
    【解决方案2】:

    Unirest API 开箱即用地支持这一点 - 使用 asString() 而不是 asJson() 以获取 HttpResponse&lt;String&gt; 的响应。

    HttpResponse<String> response = Unirest
                    .post("http://myserver.com/file")
                      .header("cache-control", "no-cache")
                      .header("Postman-Token", "02ec2fa1-afdf-4a2a-a535-353424d99400")
                    .header("Content-Type", "application/json")
                    .body("{some JSON body}")
                    .asString();
    System.out.println(response.getBody());
    

    【讨论】:

    • 有趣。显然我的日食没有输出这个!在 shell 中,我看到了响应!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-09
    相关资源
    最近更新 更多