0

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:

  • Server works fine with any UTF-8 encoded string as I have verified using Poster
  • XML is correctly encoded on client side before it written to OutputStream as I can see it in Debug mode

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);
            }
4

1 回答 1

2

几件事:

1)我假设你称之为xml的变量实际上是一个字符串。在这种情况下,您真正​​想要的是

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

2)这里似乎有一些冗余代码:

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

为什么不将所有这些替换为:

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

于 2013-08-26T15:55:05.077 回答