HttpURLConnection GET 请求得到 400 Bad Request [英] HttpURLConnection GET request getting 400 Bad Request

查看:162
本文介绍了HttpURLConnection GET 请求得到 400 Bad Request的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 HttpURLConnection 在 Java 中使用某些参数执行 GET 请求.但是,每次我这样做时,每次都会收到 400: Bad Request.我需要更改什么才能使其正常工作?

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();

我试过了:

  • 对整个查询(在 ? 之后)和仅对值使用 URLEncoder.
  • 设置内容长度标题.
  • 设置连接以使用输出并将查询作为输出.

推荐答案

在这种情况下,HTTP 400 似乎不是用来表示请求语法中的错误,而是用于表示此处描述的逻辑错误:HTTP 400(错误请求)用于逻辑错误,而不是格式错误的请求语法.

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.

这篇关于HttpURLConnection GET 请求得到 400 Bad Request的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆