简体   繁体   English

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

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

I would like to make the endpoint of the URL in that method a variable one:我想让该方法中 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;
        }
    }

Modifying it to this does not solve the case (changed 'octocat' into '{endPoint}'):将其修改为这样并不能解决问题(将 'octocat' 更改为 '{endPoint}'):

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

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

This is the GET method from my RestController:这是来自我的 RestController 的 GET 方法:

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

The browser returns this message:浏览器返回此消息:

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

Also, if I modify my URL to this:另外,如果我将 URL 修改为:

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

Then the response is this:然后回复是这样的:

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 $

Help, please.请帮忙。

For your first exception, you could try using string concatenation to append the endpoint to the URL and see if the connection opens that way:对于第一个例外,您可以尝试使用字符串连接将端点附加到 URL 并查看连接是否以这种方式打开:

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

For your second exception, it looks like you're telling GSON you have an object of type User when you actually have an array of some sort.对于您的第二个例外,当您实际上拥有某种类型的数组时,您似乎是在告诉 GSON 您有一个 User 类型的对象。 You may have to change the Type parameter in fromJson() so that gson can deserialize the json properly.您可能需要更改 fromJson() 中的 Type 参数,以便 gson 可以正确反序列化 json。 Here is an example of deserializing arrays in gson. 是在 gson 中反序列化数组的示例。

Since I see you're using spring-web and this looks like a RESTful API, I would also suggest configuring a RestTemplate Bean and injecting it into your service to make the request out to github rather than using java.net.url.由于我看到您正在使用 spring-web 并且这看起来像一个 RESTful API,我还建议配置一个 RestTemplate Bean 并将其注入您的服务以向 github 发出请求,而不是使用 java.net.url。 You can find a nice guide on spring.io for how that works.你可以在spring.io上找到一个很好的指南,了解它是如何工作的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM