1

在浏览器中点击 URI myresourceUrl 在浏览器中显示 json 内容。

要求:需要使用httpbuilder-ng的get方法调用URI的GET,response的内容为json。

此 json 文件将作为另一个任务的输入是必需的。如何实现这一点。我们是否需要任何解析器来使用 http-builder-ng 将返回的响应作为 json 获取。

预期响应格式:{"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();

我们得到的 实际格式:{name:Abc,info:{age:45,height:5.5}}

如何以预期的响应格式获得上述响应。

4

2 回答 2

0

首先,确认您的 http 请求确实返回了 JSON 响应。如果是这样,您可以使用gson库。尝试

import com.google.code.gson;
String response = gson.toJSON(http.get(LazyMap.class, cfg -> {
                cfg.getRequest().getUri().setPath(myPath);
            }));
于 2019-02-11T08:40:08.817 回答
0

默认情况下,“application/json”的内容类型将被解析,而不是作为字符串返回。您需要为内容类型定义一个自定义解析器。我使用一个返回“application/json”内容的假服务器组合了一个示例,然后展示了如何在 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);
    }
}

请注意cfg.getResponse().parser("application/json", (chainedHttpConfig, fromServer) -> textToString(chainedHttpConfig, fromServer));发生解析的行(覆盖默认行为) - 另请参阅 import import static groovyx.net.http.NativeHandlers.Parsers.textToString;

于 2019-02-14T21:28:29.627 回答