how to extract response as json from http ng-builder

643 views Asked by At

The URI myresourceUrl when hit in browser shows the json content in browser.

Requirement: Need to use the get method of httpbuilder-ng to call GET of URI and response should have the content as json.

This json file will be necessary as input for another task. How to achieve this. Do we need any parser to get the returned response as json using http-builder-ng.

Expected response format: {"name":"Abc","info":{"age":45,"height":"5.5"}}

Tried the below get request using:
// setting the request URI 
    HttpBuilder http = HttpBuilder.configure(config -> {
                    config.getRequest().setUri(myresourceUrl);
                });

String response = http.get(LazyMap.class, cfg -> {
                    cfg.getRequest().getUri().setPath(myPath);
                }).toString();

Actual format we are getting: {name:Abc,info:{age:45,height:5.5}}

How to get the response indicated above in expected response format.

2

There are 2 answers

4
Adnan S On

First, confirm that you http request is indeed returning a JSON response. If so, you can use the gson library. Try

import com.google.code.gson;
String response = gson.toJSON(http.get(LazyMap.class, cfg -> {
                cfg.getRequest().getUri().setPath(myPath);
            }));
0
cjstehno On

By default a content-type of "application/json" will be parsed rather than returned as a String. You need to define a custom parser for the content-type. I put together an example using a fake server that returns "application/json" content and then shows how to return it as a string in HttpBuilder-NG:

import com.stehno.ersatz.ErsatzServer;
import groovyx.net.http.HttpBuilder;

import static com.stehno.ersatz.ContentType.APPLICATION_JSON;
import static groovyx.net.http.NativeHandlers.Parsers.textToString;

public class Runner {

    public static void main(final String[] args) {
        final ErsatzServer server = new ErsatzServer();

        server.expectations(expects -> {
            expects.get("/something").responder(response -> {
                response.body("{\"name\":\"Abc\",\"info\":{\"age\":45,\"height\":\"5.5\"}}", APPLICATION_JSON);
            });
        });

        final String response = HttpBuilder.configure(cfg -> {
            cfg.getRequest().setUri(server.getHttpUrl());
            cfg.getResponse().parser("application/json", (chainedHttpConfig, fromServer) -> textToString(chainedHttpConfig, fromServer));
        }).get(String.class, cfg -> {
            cfg.getRequest().getUri().setPath("/something");
        });

        System.out.println(response);
        System.exit(0);
    }
}

Note the cfg.getResponse().parser("application/json", (chainedHttpConfig, fromServer) -> textToString(chainedHttpConfig, fromServer)); line which is where the parsing happens (overrides the default behavior) - see also the import import static groovyx.net.http.NativeHandlers.Parsers.textToString;.