Search code examples
javaandroidhttpurlconnectioncontent-length

content-length in HttpURLConnection


I'm trying to send a body in x-www-form-urlencoded to my local Web API. I can make GET without any problems. Here is what I do:

    String urlParameters = "user=User&label=GPU+Temp&file=src%2FDataSource0.txt&backgroundColor=rgb(255%2C255%2C255%2C0)&borderColor=rgb(255%2C255%2C255%2C0)&pointBorderColor=rgb(255%2C255%2C255%2C0)&pointHoverBackgroundColor=rgb(255%2C255%2C255%2C0)&pointHoverBorderColor=rgb(255%2C255%2C255%2C0)&min=0&max=100&stepSize=50";

    byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8"));
    int postDataLength = postData.length;
    String request = "http://192.168.1.30:6262/api/values";
    URL url = new URL(request);
    con = (HttpURLConnection) url.openConnection();
    con.setDoOutput(true);
    con.setInstanceFollowRedirects(false);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    con.setRequestProperty("charset", "utf-8");
    con.setRequestProperty("Content-Length", Integer.toString(postDataLength));
    con.connect();

java.net.ProtocolException: content-length promised 598 bytes, but received 0

So it means that I'm not sending any data in my POST, how come?


Solution

  • Using con.setRequestProperty("Content-Length", Integer.toString(postDataLength)); you're just sending the lenght of your postDataLength, you're not actually setting it's body. In order to actually send your variable to the webservice you need to do this before calling the connect():

    OutputStream os = con.getOutputStream();
    os.write(urlParameters.getBytes("UTF-8"));
    os.close();