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 = "http://www.awebsite.com/apath?p1=v1&p2=v2&p3=v3";
HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
conn.setDoInput(true);
conn.setDoOutput(false);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Host", "www.awebsite.com");
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)
    data.append(s);
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 www.awebsite.com , but it also sends an illegal/invalid value for the Host field:www.google.com. This is absolutely not allowed by the HTTP specification.

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

Required link: How to use java.net.URLConnection to fire and handle HTTP requests?

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

https://stackoverflow.com/questions/6341602/