Java – Server returned HTTP response code: 403 for URL

A simple Java program tries to download something from the internet:


  try (InputStream is = new URL(url).openStream();
       BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
      while ((line = br.readLine()) != null) {
          result.append(line);
      }
  }

But, some web servers return the following HTTP 403 errors?


Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: https://mkyong.com
	at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1919)
	at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1515)
	at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:250)
	at java.base/java.net.URL.openStream(URL.java:1139)

Solution

To fix it, add a User-Agent in the HTTP request headers as follow:

JavaDownloadSample.java

package com.mkyong;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class JavaDownloadSample {

    public static void main(String[] args) throws IOException {

        String result = downloadWebPage("https://mkyong.com");
        System.out.println(result);

    }

    private static String downloadWebPage(String url) throws IOException {

        StringBuilder result = new StringBuilder();
        String line;

        // add user agent 
        URLConnection urlConnection = new URL(url).openConnection();
        urlConnection.addRequestProperty("User-Agent", "Mozilla");
        urlConnection.setReadTimeout(5000);
        urlConnection.setConnectTimeout(5000);

        try (InputStream is = new URL(url).openStream();
             BufferedReader br = new BufferedReader(new InputStreamReader(is))) {

            while ((line = br.readLine()) != null) {
                result.append(line);
            }

        }

        return result.toString();

    }

}

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Teja Recent comment authors
newest oldest most voted
Teja
Guest
Teja

For a few use cases it’s worked and others it didn’t work. Do we have any other ways to capture the connection error?