Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java HttpURLConnection: Content Length computation

I'm currently developing a library for the bitbucket issues RESTful API. I made good progress and now I'm going to tackle the section Updating an Issue which demands an HTTP PUT Request.

Now I'm stuck because of the HTTP Error Code 411 Length Required. After a bit of googling, I found the following code example:

// CORRECT: get a UTF-8 encoded byte array from the response
// String and set the content-length to the length of the
// resulting byte array.
String response = [insert XML with UTF-8 characters here];
byte[] responseBytes;
try {
    responseBytes = response.getBytes("UTF-8");
}
catch ( UnsupportedEncodingException e ) {
    System.err.print("My computer hates UTF-8");
}

this.contentLength_ = responseBytes.length;

Now my question: What is exactly measured?

  • the query string
  • the urlencoded query string
  • only the values of the parameters...??

And is connection.setRequestProperty("Content-Length", String.valueOf(<mycomputedInt>)); an appriopate way of setting the content length attribute?

Examples appreciated. Thanks in advance.


edit:

For instance, you could explain computation with the following curl example from the bitbucket wiki entry:

curl -X PUT -d "content=Updated%20Content" \
https://api.bitbucket.org/1.0/repositories/sarahmaddox/sarahmaddox/issues/1/
like image 920
f4lco Avatar asked Jun 15 '11 08:06

f4lco


People also ask

How do you calculate content length?

As bytes are represented with two hexadecimal digits, one can divide the number of digits by two to obtain the content length (There are 12 hexadecimal digits in "48656c6c6f21" which equates to six bytes, as indicated in the header "Content-Length: 6" sent from the server).

How do I set the content length in Java?

To manually pass the Content-Length header, you need to add the Content-Length: [length] and Content-Type: [mime type] headers to your request, which describe the size and type of data in the body of the POST request.

What is content length in Java?

The Content-Length header indicates the size of the message body, in bytes, sent to the recipient.

What is HttpURLConnection in java?

public abstract class HttpURLConnection extends URLConnection. A URLConnection with support for HTTP-specific features. See the spec for details. Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances.


1 Answers

Your are doing the request, right. The content-length is the number of bytes of your request body. In your case

int content-length = "content=Updated%20Content".getBytes("UTF-8").length;

What is exactly measured?

the url encoded query string (when in the request/entity body)

like image 135
webstrap Avatar answered Sep 30 '22 20:09

webstrap