M. Atif Riaz
M. Atif Riaz

Reputation: 502

Encoding issue while writing data to OutputStream

I am working on a Balckberry mobile application. It get some data and post it to a Server application on java.io.OutputStream using javax.microedition.io.Connection object. Although I am setting "Content-Type" property for Connection but still cannot get correct encoded string on server side

Please note that:

Anyone can find a glitch Below is the code.

            // Client side code

            // xml is String xml and is correctly encoded, I can see Arabic or Chinese character it in debug mode
            byte[] requestByte = xml.getBytes();

            // compress request bytes array
            // initialize connection

            // set connection properties
            con.setRequestMethod(HttpConnection.POST);
            con.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setRequestProperty("Content-Encoding", "UTF-8");

            os = con.openOutputStream();
            InputStream in = new ByteArrayInputStream(requestByte);
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = in.read(buffer)) > 0) {
                os.write(buffer, 0, bytesRead);
            }

Upvotes: 0

Views: 130

Answers (1)

Peter Strange
Peter Strange

Reputation: 2650

Couple of things:

1) I presume that the variable what you call xml, is actually a String. In which case what you actually want is

byte[] requestByte = xml.getBytes("UTF-8");

2) There seems to be some redundant code here:

        InputStream in = new ByteArrayInputStream(requestByte);
        byte[] buffer = new byte[4096];
        int bytesRead = 0;
        while ((bytesRead = in.read(buffer)) > 0) {
            os.write(buffer, 0, bytesRead);
        }

Why not replace all this with:

os.write(requestByte, 0, requestByte.length);

Upvotes: 2

Related Questions