OutputStreamWriter在HttpURLConnection输出流中写入特殊字符

时间:2013-05-07 21:49:55

标签: java httpurlconnection bufferedwriter content-length

当我将字符串写入HttpURLConnection输出流时,会发生一些奇怪的事情。我为HttpURLConnection对象设置了Content-Length请求属性,如下面的代码所示,但是当我将一些字符串(在我的情况下是一个XML内容作为字符串)写入HttpURLConnection输出流时,一些特殊字符是插入到字符串的结尾和开头。字符为1a\r\n。因此,当请求到达服务器端时,Content-Length属性不会反映正确的字符串长度。

这是一些Java bug吗?

我的代码,其中urlConnectionHttpURLConnection的实例,而payLoad是包含XML的字符串变量:

urlConnection.setConnectTimeout(20000);
urlConnection.setReadTimeout(30000);
urlConnection.setChunkedStreamingMode(0);
urlConnection.setRequestMethod("POST");

urlConnection.setRequestProperty("Content-Type", "application/xml");
urlConnection.setRequestProperty("Accept", application/json");

urlConnection.setRequestProperty("Content-Length", String.valueOf(payLoad.getBytes().length));

urlConnection.setUseCaches(false);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);

// Send request
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
bw.write(payLoad);
bw.flush();
bw.close();

int returnCode = urlConnection.getResponseCode();

XML作为我发送的字符串:

   '<parameters><endMac value="7A:79:00:00:00:00"/><endMac value="7A:79:00:00:00:00"/><endMac value="00:00:00:00:00:00:00:E0"/><endMac value="00:00:00:00:00:00:00:E0"/><endMac value="00:00:00:00:00:00:00:E0"/><endMac value="D8:5D:4C:95:BC:BD"/></parameters>'

我收到的XML:

   'fd\r\n<parameters><endMac value="7A:79:00:00:00:00"/><endMac value="7A:79:00:00:00:00"/><endMac value="00:00:00:00:00:00:00:E0"/><endMac value="00:00:00:00:00:00:00:E0"/><endMac value="00:00:00:00:00:00:00:E0"/><endMac value="D8:5D:4C:95:BC:BD"/></paramet'

0 个答案:

没有答案