Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get raw JSON text from Unirest response in Java

I'm trying to send a POST request to a server, get the response, and parse it (it is a JSON file).

I am using Unirest for my POST request, simply as below:

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

But I have problems getting the raw JSON text (I want to use JSONPath to parse the response).

How can I do that? All my attempts calling toString() methods failed so far.

like image 304
Tina J Avatar asked Mar 05 '23 21:03

Tina J


2 Answers

The Unirest API supports this out of the box - Use asString() instead of asJson() to get the response as 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());
like image 137
Neeraj Avatar answered Mar 07 '23 15:03

Neeraj


You can do it like this:

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");
like image 45
frederikdebacker Avatar answered Mar 07 '23 16:03

frederikdebacker