我是 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());
}
}