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