如何将一个变量终端点设置到我的URL以用于HTTP GET方法?

huangapple go评论71阅读模式
英文:

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("无法返回所需输出。");
            return null;
        } else {
            logger.info("返回了输出。");
            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();
    }
浏览器返回此消息
出现了意外错误类型=内部服务器错误状态=500)。
https://api.github.com/users/{endPoint}
另外如果我将 URL 修改为以下内容
URL url = new URL("https://api.github.com/users");
则响应如下所示
出现了意外错误类型=内部服务器错误状态=500)。
java.lang.IllegalStateException: 在第1行第2列处期望的是 BEGIN_OBJECT但实际是 BEGIN_ARRAY路径为 $
请帮忙谢谢
英文:

I would like to make the endpoint of the URL in that method a variable one:

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}'):

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:

@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 = 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.

答案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上找到一个关于如何使用的很好的指南。

英文:

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 = 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. You may have to change the Type parameter in fromJson() so that gson can deserialize the json properly. Here is an example of deserializing arrays in 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. You can find a nice guide on spring.io for how that works.

huangapple
  • 本文由 发表于 2020年8月31日 01:21:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/63660144.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定