Search code examples
javaappletjappletcontent-lengthhttp-content-length

Java Applet 411 Content Length


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

}

Solution

  • Request uri includes query , can use GET method.

    connection.setRequestMethod("POST"); // modify to GET
    connection.setRequestProperty("Content-Length", length); //remove the line
    

    if use POST method, include 'content-length' heade, must send data.

    for example:

    public void sendPoints1(int w, int p){
    
        try {
            String url = "http://somename.com:309/api/Results";
            //value type is int ,don't need URLEncoder.
            byte[] data = ("key="+w+"&value="+p).getBytes("UTF-8");
    
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Length", data.length);
     connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //URLencode...
            OuptputStream out = connection.getOutputStream();
            out.write(data);
            out.flush();
            InputStream in = connnection.getInputStream();
            //read .....
            System.out.println("Responce Code:    " + connection.getResponseCode());
            System.out.println("Responce Message: " + connection.getResponseMessage());
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    
    }