繁体   English   中英

如何从Java中的Unirest响应中获取原始JSON文本

[英]How to get raw JSON text from Unirest response in Java

我正在尝试向服务器发送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()方法的所有尝试都失败了。

你可以这样做:

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");

Unirest API支持开箱即用 - 使用asString()而不是asJson()来获取响应为HttpResponse<String>

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());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM