How to get raw JSON text from Unirest response in Java

Tina J :

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.

Neeraj :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=73929&siteId=1