简体   繁体   English

HttpURLConnection GET 请求得到 400 错误请求

[英]HttpURLConnection GET request getting 400 Bad Request

I am trying to do a GET request with some parameters in Java using HttpURLConnection.我正在尝试使用 HttpURLConnection 在 Java 中使用一些参数执行 GET 请求。 Everytime I do this however, I get a 400: Bad Request each time.但是,每次我这样做时,我都会收到 400: Bad Request 。 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.在整个查询(在?之后)和值上使用 URLEncoder。
  • Setting the content length header.设置内容长度 header。
  • Setting the connection to use output and putting the query as the output.将连接设置为使用 output 并将查询设置为 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 .在这种情况下,HTTP 400 似乎不是用来表示请求语法中的错误,而是表示此处描述的逻辑错误: HTTP 400 (bad request) for logical error, not malformed request syntax

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 .该代码尝试打开与www.awebsite.com的连接,但它也会发送 Host 字段的非法/无效值: www.google.com This is definitely not allowed by the HTTP specification. HTTP 规范绝对不允许这样做。

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.您必须更正此问题,以确保www.awebsite.com上的服务器接收到正确的标头集,以便它可以处理您的请求。

Obligatory link : How to use java.net.URLConnection to fire and handle HTTP requests?必填链接如何使用 java.net.URLConnection 触发和处理 HTTP 请求?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM