在尝试编写中文字符时,OutputStreamWriter的flush方法抛出IOException

时间:2011-01-19 13:57:36

标签: android soap httpurlconnection cjk ioexception

下面是我用来在我的Android应用程序中发送SOAP请求的代码,它可以正常处理除一个以外的所有请求。当wr.flush();变量中有中文字符时,此代码会在requestBody上抛出 IOException:Content-length exceeded

在这种情况下,内容长度为409

            URL url = new URL(Constants.HOST_NAME);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // Modify connection settings
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            connection.setRequestProperty("SOAPAction", soapAction);

            String requestBody = new String(soapRequest.getBytes(),"UTF-8");
            int lngth = requestBody.length();
            connection.setRequestProperty("Content-Length", (""+lngth));

            // Enable reading and writing through this connection
            connection.setDoInput(true);
            connection.setDoOutput(true);

            // Connect to server
            connection.connect();

            OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            wr.write(requestBody);
            wr.flush();
            wr.close();

当字符串中有中文字符时,有什么问题可以解决?

编辑:我删除了'content-lenght'标题字段,但它有效,但为什么?

3 个答案:

答案 0 :(得分:3)

此代码将请求的Content-Length属性设置为消息的字符串表示形式中的字符数:

String requestBody = new String(soapRequest.getBytes(),"UTF-8");
int lngth = requestBody.length();
connection.setRequestProperty("Content-Length", (""+lngth));

然后在写入之前将该字符串表示转换回字节:

OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");

所以你最后写了更多的字节,然后你声称。任何非ASCII字符都会遇到同样的问题。相反,你应该做这样的事情(复制粘贴,因此可能有语法错误):

byte[] message = soapRequest.getBytes();
int lngth = message.length;
connection.setRequestProperty("Content-Length", (""+lngth));

// ...

connection.getOutputStream().write(message);

答案 1 :(得分:1)

简化另一个答案:Content-Length必须是以字节为单位的长度,并且您在chars中指定长度(Java的16位字符类型)。总的来说,这些是不同的。由于UTF-8是一种可变字节长度编码,因此除了基本的7位ASCII范围之外,还有其他区别。另一个答案显示了编写代码的正确方法。

答案 2 :(得分:0)

我的猜测是你没有将中文转换成utf-8。如果您支持用户在字段中输入双倍字符集和扩展字符集,则需要确保将输入从这些字符集(ASCII,UNICODE或UCS)转换为UTF-8。

确定正在使用的字符编码后,您可以使用以下内容:

FileInputStream(inputFile), "inputencoding");
Writer output = new OutputStreamWriter(new FileOutputStream(outputFile), "outputencoding");

Reference

创建用于读/写的流以在两者之间进行转换。

另一种方法是研究设置控制http请求语言的请求属性。我对此并不了解。