I have tried to find whether a url exists or not with the following code. The requirement is to find whether a file exists or not in the url.

    try{
         HttpURLConnection.setFollowRedirects(false);
         HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
         con.setRequestMethod("HEAD");
         responseCode = con.getResponseCode();
         return Response.ok(Integer.toString(responseCode)).build();
    }
    catch(Exception e){
        return Response.ok(e.getMessage()).build();
    }

This works perfectly if the url doesn't contain any spaces/special characters. But if it has any, it always returns code 404. Can I know how this can be solved? Thanks in advance.

有帮助吗?

解决方案

URLs with spaces in them are invalid. The correct way to create a properly encoded URL from a filename that may contain spaces is URI.toASCIIString(), and then passing that to new URL(), making sure to use a URI constructor that takes multiple arguments so the filename part gets encoded: see the Javadoc.

However I question the requirement. The best way to test whether any resource is available is to try to use it. In this case presumably you are going to read from the URL if it exists, so just do that and catch the FileNotFoundException.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top