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();
}
}
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?
thanks, it works
Hello, I used your solution and now I get the error: HTTP/1.1 406 Not Acceptable.
I’m using apache httpclient
HttpGet httpget = new HttpGet(urlFile);
httpget.addHeader(“User-Agent”, “Mozilla/5.0”);
HttpResponse response = httpClient.execute(httpget);
Thank you for your help.