且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

HttpURLConnection GET请求获得400错误请求

更新时间:2022-10-29 09:19:00

看来,在这种情况下,HTTP 400被用来不表示请求语法中的错误,但是这里描述了逻辑错误: HTTP 400(错误的请求)的逻辑错误,而不是格式错误的请求语法


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.

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.