Question

I am trying to do a GET request with some parameters in Java using HttpURLConnection. Everytime I do this however, I get a 400: Bad Request each 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 have tried:

  • Using URLEncoder on the whole query (after the ?) and just on the values.
  • Setting the content length header.
  • Setting the connection to use output and putting the query as the output.
Was it helpful?

Solution 2

It seems that in this case the HTTP 400 is being used not to signify an error in the request syntax, but a logical error as described here: HTTP 400 (bad request) for logical error, not malformed request syntax.

OTHER TIPS

The code attempts to open a connection to www.awebsite.com, but it also sends illegal/invalid values for the Host field: www.google.com. This is definitely not allowed by the HTTP specification.

You would have to correct this, to ensure that the server at www.awebsite.com receives the correct set of headers, so that it can process your request.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top