2

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?

BeGreen
  • 765
  • 1
  • 13
  • 39

2 Answers2

3

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();
LS_
  • 6,763
  • 9
  • 52
  • 88
0

You need do this:

            body = datos.toString();
            content_bytes = body.getBytes("UTF-8");
            content_length = content_bytes.length;



            // establecer headers.
            connection.setRequestProperty( "Content-Type", "application/json; charset=utf-8" );
            connection.setRequestProperty( "Content-Length", Integer.toString( content_length  ) );

.....

            dataOutputStream = new DataOutputStream( connection.getOutputStream() );
            dataOutputStream.write(body.getBytes("UTF-8"));
Saul Euan
  • 11
  • 3
  • Hi, welcome to Stack Overflow! Please [edit] your answer to elaborate a bit on how this code works and how it will solve the problem. Thank you! – grooveplex Aug 08 '19 at 16:08