AbuMariam
AbuMariam

Reputation: 3678

Java HTTP PUT not sending the data

I want to send some data to a server over HTTP PUT (calling a REST web service). Below is the code..

URL urlObj = new URL("http://99.66.66.238:8443/media/service");
          HttpURLConnection conn = (HttpURLConnection) urlObj
                .openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("PUT");
        conn.setRequestProperty("accept-charset", "UTF-8");
        conn.setRequestProperty("content-type",
                "application/x-www-form-urlencoded");

        String userPassword = username + ":" + password;
        byte[] authEncBytes = Base64.encodeBase64(userPassword.getBytes());
        String authStringEnc = new String(authEncBytes);
        conn.setRequestProperty("Authorization", "Basic " + authStringEnc);

        OutputStreamWriter writer = new OutputStreamWriter(
                conn.getOutputStream(), "UTF-8");
        writer.write(requestXML);
        conn.getOutputStream().flush();

But on the other side, they do not get the data. They only see..

PUT /media/service HTTP/1.1
accept-charset: UTF-8
content-type: application/x-www-form-urlencoded
Authorization: Basic cm10dGVzdDpwYXNzd29yZA=3D=3D
Cache-Control: no-cache
Pragma: no-cache
User-Agent: Java/1.6.0_13
Accept: text/html, image/gif, image/jpeg, *; q=3D.2, */*; q=3D.2
Connection: keep-alive
Content-Length: 0 

Notice how the Content-Length is 0. Can you please tell me why the data is not going through? Is there anyway I can see exactly what I am sending?

Thanks.

Upvotes: 2

Views: 436

Answers (2)

Paul Vargas
Paul Vargas

Reputation: 42040

You need too flush out all the buffered output. Maybe you only want to use:

conn.getOutputStream().write(requestXML.getBytes("UTF-8"));

This flush the output automatically.

Upvotes: 1

Rudi Angela
Rudi Angela

Reputation: 1483

Shouldn't you call the flush() on the writer instead of the connection's output stream? Seems to me the data might still be in the writer's buffer when you flush the connection's output stream, which would explain the 0 bytes sent.

Upvotes: 0

Related Questions