java.net.MalformedURLException:无协议:但 URL 没问题,该方法适用于其他 GET 请求

java.net.MalformedURLException: no protocol: BUT the URL is fine and the method works for other GET Requests

我写了下面的代码:

public String sendGet(String url) throws Exception {
        HttpURLConnection httpClient = (HttpURLConnection) new URL(url).openConnection();
        httpClient.setRequestMethod("GET");
        int responseCode = httpClient.getResponseCode();
        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(httpClient.getInputStream()))) {
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                response.append(line);
            }
            return response.toString();
        }
}

它对我的 GET 请求非常有效,但不适用于此: https://www.lichess.org/api/user/{USERNAME}

如果我发送它,我会收到以下错误:

PM org.apache.catalina.core.StandardWrapperValve 调用 SCHWERWIEGEND:Servlet.service() for servlet [dispatcherServlet] 在路径 [] 的上下文中抛出异常 java.net.MalformedURLException:无协议:{预期响应}

预期的响应在错误消息中。

我将此 GET 请求从 lichess.org 发送到外部 API,并尝试使用 Postman 和我的浏览器发送该请求,它有效。问题一定出在我的代码中。 (使用Java 8和java.net)奇怪的是有时能用有时不能用

你知道要做什么吗?

感谢您的帮助。

我认为这是一个具体案例。 URL https://lichess.org/api/user/{georges} in browser does not work as well while https://lichess.org/api/user/georges 会(没有 {})。与您的代码片段相同。

不允许在 URL 中使用大括号。

它们有时用于 URI 模板中的变量名,您的示例 URL 看起来确实如此。因此“{USERNAME}”可能需要替换为...用户名,并且在执行此操作时,需要删除括号。