如何为 HTTP GET 方法设置可变端点到我的 URL?

How to set a variable endpoint to my URL for HTTP GET method?

我想将该方法中 URL 的端点设为变量一:

public User fetchUser() throws IOException {

        URL url = new URL("https://api.github.com/users/octocat");
        InputStreamReader reader = new InputStreamReader(url.openStream());

        User user = new Gson().fromJson(reader, User.class);
        if (user == null) {
            logger.error("Could not return desired output.");
            return null;
        } else {
            logger.info("The output returned.");
            return user;
        }
    }

修改成这样并不能解决问题(将'octocat'改为'{endPoint}'):

public User fetchUser(@PathVariable String endPoint) throws IOException {

        URL url = new URL("https://api.github.com/users/{endPoint}");

这是来自我的 RestController 的 GET 方法:

@GetMapping("/user/info/{login}")
    public User getUser(@PathVariable String login) throws IOException {
        return userService.fetchUser();
    }

浏览器returns这条消息:

There was an unexpected error (type=Internal Server Error, status=500).
https://api.github.com/users/{endPoint}

此外,如果我将 URL 修改为:

URL url = new URL("https://api.github.com/users");

那么响应是这样的:

There was an unexpected error (type=Internal Server Error, status=500).
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

请帮忙。

对于第一个例外,您可以尝试使用字符串连接将端点附加到 URL 并查看连接是否以这种方式打开:

URL url = new URL("https://api.github.com/users/" + endpoint);

对于你的第二个异常,看起来你在告诉 GSON 你有一个 User 类型的对象,而你实际上有一个某种类型的数组。您可能必须更改 fromJson() 中的 Type 参数,以便 gson 可以正确反序列化 json。 Here是gson中反序列化数组的例子

因为我看到你正在使用 spring-web 并且这看起来像 RESTful API,我还建议配置一个 RestTemplate Bean 并将其注入到你的服务中以使请求 github 而不是使用 java.net.url。您可以在 spring.io 上找到一个很好的指南,了解它是如何工作的。