0

我想在该方法中使 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();
    }

浏览器返回此消息:

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 $

请帮忙。

4

1 回答 1

1

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

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

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

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

于 2020-08-30T18:18:28.147 回答