I am new to Java. I wrote an applet with a gui that sends results (int w and int p) to a server, and I get the "411 Length Required" error. What am I doing wrong? How do you set a Content-Length?
This is the method that communicates with the server:
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());
}
}
I'm not 100% sure why you're getting a 411 error code, but it probably has to do with the fact that you are not sending any content with your POST. The content-length header should be the length in bytes of the body of the request. You are setting it to the length of the url!
Either change the request to a GET or put the query into the body of the request instead of into the url itself. If you do the latter, set the content-length to the length of the body only.
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());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With