2

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.

1
  • Have you tried setting the Content-Length and Content-type headers? It may be the case that the server isn't bothering to read anything because the headers aren't set. Commented Apr 2, 2014 at 18:39

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Paul, that worked. The other side got the output. Just one problem now is that the words "3D" seem to be appended to the XML's first line.. <?xml version=3D"1.0" encoding=3D"UTF-8"?>. Would you why know this is happening?
You can use the class javax.mail.internet.MimeUtility. eg. ByteArrayInputStream is = new ByteArrayInputStream(str.getBytes("UTF-8")); InputStream out = MimeUtility.decode(is, "quoted-printable");
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.