gpt4 book ai didi

java - HttpURLConnection GET 请求得到 400 Bad Request

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:25:37 25 4
gpt4 key购买 nike

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

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。
  • 设置内容长度 header 。
  • 将连接设置为使用输出并将查询作为输出。

最佳答案

该代码尝试打开与 www.awebsite.com 的连接,但它也会为 Host 字段发送非法/无效值:www.google.com。这是 HTTP 规范绝对不允许的。

您必须更正此问题,以确保位于 www.awebsite.com 的服务器收到正确的 header 集,以便它可以处理您的请求。

必填链接:How to use java.net.URLConnection to fire and handle HTTP requests?

关于java - HttpURLConnection GET 请求得到 400 Bad Request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6341602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com