gpt4 book ai didi

Java Applet 411 内容长度

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:10:51 26 4
gpt4 key购买 nike

我是 Java 新手。我写了一个带有 gui 的小程序,将结果(int w 和 int p)发送到服务器,我得到了“411 Length Required”错误。我究竟做错了什么?如何设置内容长度?

这是与服务器通信的方法:

public void sendPoints1(int w, int p){

try {
String url = "http://somename.com:309/api/Results";
String charset = "UTF-8";
String query = String.format("?key=%s&value=%s",
URLEncoder.encode(String.valueOf(w), charset),
URLEncoder.encode(String.valueOf(p), charset));
String length = String.valueOf((url + query).getBytes("UTF-8").length);

HttpURLConnection connection = (HttpURLConnection) new URL(url + query).openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Length", length);
connection.connect();
System.out.println("Responce Code: " + connection.getResponseCode());
System.out.println("Responce Message: " + connection.getResponseMessage());
} catch (Exception e) {
System.err.println(e.getMessage());
}

}

最佳答案

我不是 100% 确定您收到 411 错误代码的原因,但这可能与您没有通过 POST 发送任何内容有关。内容长度 header 应该是请求正文的字节长度。您正在将其设置为 url 的长度!

将请求更改为 GET 或将查询放入请求正文而不是放入 url 本身。如果您选择后者,请将内容长度设置为仅正文的长度。

public void sendPoints1(int w, int p){

try {
String url = "http://somename.com:309/api/Results";
String charset = "UTF-8";
String query = String.format("key=%s&value=%s",
URLEncoder.encode(String.valueOf(w), charset),
URLEncoder.encode(String.valueOf(p), charset));
byte[] queryBytes = query.getBytes("UTF-8");
String length = String.valueOf((url + query).getBytes("UTF-8").length);

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Length", length);
OutputStream os = connection.getOutputStream();
os.write(queryBytes);
os.flush();
connection.connect();
System.out.println("Responce Code: " + connection.getResponseCode());
System.out.println("Responce Message: " + connection.getResponseMessage());
} catch (Exception e) {
System.err.println(e.getMessage());
}

}

关于Java Applet 411 内容长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13872823/

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