将发布数据从一个java servlet写入另一个

我正在尝试编写一个servlet,它将通过POST将XML文件(xml格式化的字符串)发送到另一个servlet。 (非必要的xml生成代码替换为“Hello there”)

StringBuilder sb= new StringBuilder(); sb.append("Hello there"); URL url = new URL("theservlet's URL"); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Length", "" + sb.length()); OutputStreamWriter outputWriter = new OutputStreamWriter(connection.getOutputStream()); outputWriter.write(sb.toString()); outputWriter.flush(); outputWriter.close(); 

这导致服务器错误,并且永远不会调用第二个servlet。

使用像HttpClient这样的库,这种事情要容易得多。 甚至还有一个XML代码示例 :

 PostMethod post = new PostMethod(url); RequestEntity entity = new FileRequestEntity(inputFile, "text/xml; charset=ISO-8859-1"); post.setRequestEntity(entity); HttpClient httpclient = new HttpClient(); int result = httpclient.executeMethod(post); 

我推荐使用Apache HTTPClient ,因为它是一个更好的API。

但要解决当前的问题:尝试调用connection.setDoOutput(true); 打开连接后。

 StringBuilder sb= new StringBuilder(); sb.append("Hello there"); URL url = new URL("theservlet's URL"); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Length", "" + sb.length()); OutputStreamWriter outputWriter = new OutputStreamWriter(connection.getOutputStream()); outputWriter.write(sb.toString()); outputWriter.flush(); outputWriter.close(); 

HTTPpost上传流的内容及其机制似乎并不像您期望的那样。 您不能只将文件写为post内容,因为POST对于如何发送POST请求中包含的数据有非常具体的RFC标准。 它不仅仅是内容本身的格式化,而且也是它如何“写入”输出流的机制。 很多时候POST现在是用块写的。 如果你看一下Apache的HTTPClient的源代码,你会看到它是如何编写块的。

结果是存在具有内容长度的怪癖,因为内容长度增加了识别块的少量数字和随机的小字符序列,这些字符在流写入时划分每个块。 查看较新的Java版本的HTTPURLConnection中描述的其他一些方法。

http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html#setChunkedStreamingMode(int)

如果您不知道自己在做什么并且不想学习它,那么处理添加像Apache HTTPClient这样的依赖关系确实会变得更容易,因为它抽象了所有复杂性并且正常工作。

别忘了使用:

 connection.setDoOutput( true) 

如果你打算发送输出。