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.
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());
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With