我有一个自己编写的协议,使用Java 1.6中的HttpURLConnection和Jetty 6.1.26来POST一块XML作为请求并接收一块XML作为响应。XML的大小约为5KB。
当在世界不同地方的Linux EC2实例上同时运行发送方和接收方时,我发现大约0.04%的请求中Jetty处理程序将XML请求(POST体)视为空字符串。我已经检查过,客户端输出表明它一直尝试发送正确(> 0长度)的XML请求字符串。
我还通过在本地(Win 8)循环我的JUnit测试来重现了这个问题。
我认为错误可能是以下原因之一:
- 缓冲区的误用
- HttpURLConnection的错误
- 网络错误
- Jetty的错误
- 我在代码中做了一个随机的头脑发热的愚蠢的事情
相关代码如下:
客户端
connection = (HttpURLConnection) (new URL (url)).openConnection();
connection.setReadTimeout(readTimeoutMS);
connection.setConnectTimeout(connectTimeoutMS);
connection.setRequestMethod("POST");
connection.setAllowUserInteraction(false);
connection.setDoOutput(true);
// Send request
byte[] postBytes = requestXML.getBytes("UTF-8");
connection.setRequestProperty("Content-length", "" + postBytes.length);
OutputStream os = connection.getOutputStream();
os.write(postBytes);
os.flush();
os.close();
// Read response
InputStream is = connection.getInputStream();
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer, "UTF-8");
is.close();
connection.disconnect();
return writer.toString();
服务器 (Jetty 处理程序)
public void handle(java.lang.String target, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, int dispatch) {
InputStream is = request.getInputStream();
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer, "UTF-8");
is.close();
String requestXML = writer.toString();
// requestXML is 0 length string about 0.04% of time
有人能想到为什么我会随机收到一个空字符串的请求吗?
谢谢!
编辑
我增加了一些跟踪,当错误发生时getContentLength()返回-1,但客户端输出仍然显示发送的字节数是正确的。