Search code examples
javahttpservletsget

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


I wrote the following Code:

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();
        }
}

And it works very fell for my GET Requests, but not for this : https://www.lichess.org/api/user/{USERNAME}

If I send it, I get the following Error:

PM org.apache.catalina.core.StandardWrapperValve invoke SCHWERWIEGEND: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception java.net.MalformedURLException: no protocol: {Expected Response}

The expected response is in the error msg.

I send this GET request to an external API from lichess.org and I tryed the request with Postman and in my browser and it works. The problem must be in my code. (Using Java 8 and java.net) It's strange that sometimes it works and sometimes it doesn't.

Do you know what to do ?

Thanks for your help.


Solution

  • I think this is specific case. URL https://lichess.org/api/user/{georges} in browser does not work as well while https://lichess.org/api/user/georges does (without {}). Same with your code snippet.