Kong / unirest-java

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

Transform body content before parsing #468

Closed gtaylor1981 closed 1 year ago

gtaylor1981 commented 1 year ago

I'd like to be able to change the content of the response before it gets parsed. This would be of help if the JSON that is returned is malformed in a known way, or if it has been encoded/encrypted.

Looking at the source code, a straightforward way to implement this might be to add an asJson(Function<String, String> transformer) method.

For example, if a REST API returns { "result": 1234 } { "error": "none"} It is recognised as invalid JSON so cannot be mapped by asJson(). Then I could write:

.post("url")
.asJson(jsonString -> jsonString.split(" \\{")[0])

This would be fine for my purposes but would work only for asJson() and leaves the other API methods without this useful feature. A more general approach (that works more like interceptors) might look like:

.post("url")
.transformRawResponse(rawResponse -> convert(rawResponse.getContentAsString().split(" \\{")[0]))
.asJson()

(Here, I'm not sure what the transformer should return so I used convert() as a placeholder.)

ryber commented 1 year ago

The JSON Object has a public constructor so an easy way to do this would be:

JsonNode e = Unirest.get("http://localhost")
                .asString()
                .mapBody(b -> {
                    String newBody = b.split(" \\{")[0];
                    return new JsonNode(newBody);
                });
gtaylor1981 commented 1 year ago

Thanks for the suggestion, it's good enough to solve my problem. I won't close this issue in case you think the generalised 'pre-transform' or asJson(transform) suggestions are still worth investigating/implementing, otherwise feel free to close. Thanks for your time.