【问题标题】:Encoding issue while writing data to OutputStream将数据写入 OutputStream 时出现编码问题
【发布时间】:2013-08-26 23:55:05
【问题描述】:

我正在开发一个 Balckberry 移动应用程序。它获取一些数据并使用javax.microedition.io.Connection 对象将其发布到java.io.OutputStream 上的服务器应用程序。虽然我正在为Connection 设置“Content-Type”属性,但仍然无法在服务器端获取正确的编码字符串

请注意:

  • 服务器可以很好地处理任何UTF-8 编码的字符串,正如我已经验证的那样 使用Poster
  • XML 在写入 OutputStream 之前已在客户端正确编码,我可以在调试模式下看到它

任何人都可以找到故障以下是代码。

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

【问题讨论】:

    标签: blackberry java-me


    【解决方案1】:

    几件事:

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

    【讨论】:

    • 是的,成功了。但是是否也需要在Content-EncodingConnection 属性中进行设置。关于冗余代码:在这个应用程序中,大多数时候设备发送大量数据,对于慢速连接,我们以较小的块读取数据
    猜你喜欢
    • 2018-10-14
    • 2018-10-17
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多