Java – HttpURLConnection GET requests get 400 Bad Requests

Here is a solution to the problem: HttpURLConnection GET requests get 400 Bad Requests.

I’m trying to do a GET request with some parameters in Java using HttpURLConnection. However, every time I do this, I get a 400: Bad Request every time.
What do I need to change to make it work?

String url = "";
HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
conn.setRequestProperty("Host", "");
conn.setRequestProperty("User-Agent", "Mozilla/4.0");
conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-us,en;q=0.5");
conn.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
conn.setRequestProperty("Keep-Alive", "115");
conn.setRequestProperty("Connection", "keep-alive");
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder data = new StringBuilder();
String s = "";
while((s = br.readLine()) != null)
String pageData = data.toString();

I tried:

  • Use URLEncoder for the entire query (after the ? and only for values.
  • Set the content length header.
  • Set the connection to use output and query as output.

The best answer

The code attempts to open a connection to , but it also sends an illegal/invalid value for the Host This is absolutely not allowed by the HTTP specification.

You must correct this problem to ensure that the server located at receives the correct set of headers so that it can process your request.

Required link: How to use to fire and handle HTTP requests?

Regarding java – HttpURLConnection GET requests get 400 Bad Requests, we found a similar issue on Stack Overflow: