Kong / unirest-java

Unirest in Java: Simplified, lightweight HTTP client library.
http://kong.github.io/unirest-java/
MIT License
2.61k stars 594 forks source link

Process error response body #182

Closed petrdvorak closed 5 years ago

petrdvorak commented 7 years ago

Our RESTful API can return either 200-OK response, or a 400-BadRequest response. Both of these can have a response body - one of a OKResponse type, other of ErrorResponse type.

It would be nice to document how to process this API with unirest - how do I serialize OKResponse when server returns 200-OK, and how do I serialize ErrorResponse in case of 400-BadRequest.

toonsevrin commented 7 years ago

Would HttpResponse#getRawBody() solve your problem? With apache commons you can write it to a string like this: String body = IOUtils.toString(res.getRawBody(), //encoding//);

petrdvorak commented 7 years ago

@toonsevrin Yes - this is what I currently use and it works

ObjectMapper mapper = new ObjectMapper();
ErrorResponse error = mapper.readValue(response.getRawBody(), ErrorResponse.class);

However, it feels weird I have to implement this myself, when OK response is serialized nicely. I believe everyone has to deal with the issue and therefore, if the library managed to deal with it once, it would save a lot of time... ;-)

ryber commented 5 years ago

Hello, this should be resolved or addressed in Unirest 2. Please see the upgrade guide for important changes.