Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to check if a URL exists or returns 404 with Java?
    text
    copied!<pre><code>String urlString = "http://www.nbc.com/Heroes/novels/downloads/Heroes_novel_001.pdf"; URL url = new URL(urlString); if(/* Url does not return 404 */) { System.out.println("exists"); } else { System.out.println("does not exists"); } urlString = "http://www.nbc.com/Heroes/novels/downloads/Heroes_novel_190.pdf"; url = new URL(urlString); if(/* Url does not return 404 */) { System.out.println("exists"); } else { System.out.println("does not exists"); } </code></pre> <p>This should print</p> <pre><code>exists does not exists </code></pre> <p><strong>TEST</strong></p> <pre><code>public static String URL = "http://www.nbc.com/Heroes/novels/downloads/"; public static int getResponseCode(String urlString) throws MalformedURLException, IOException { URL u = new URL(urlString); HttpURLConnection huc = (HttpURLConnection) u.openConnection(); huc.setRequestMethod("GET"); huc.connect(); return huc.getResponseCode(); } System.out.println(getResponseCode(URL + "Heroes_novel_001.pdf")); System.out.println(getResponseCode(URL + "Heroes_novel_190.pdf")); System.out.println(getResponseCode("http://www.example.com")); System.out.println(getResponseCode("http://www.example.com/junk")); </code></pre> <p>Output</p> <p>200<br> 200<br> 200<br> 404</p> <h1>SOLUTION</h1> <p>Add the next line before .connect() and the output would be 200, 404, 200, 404</p> <pre><code>huc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)"); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload