簡體   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