从一个Java Servlet向另一个Servlet写入POST数据

9

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

   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从未被调用。

4个回答

13

使用像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);

8
我建议使用 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();

2
不要忘记使用:

connection.setDoOutput( true)

如果您打算发送输出。


2
HTTP POST上传流的内容和机制似乎不是您所期望的。您不能只将文件写入POST内容,因为POST有非常特定的RFC标准,规定了POST请求中包含的数据应该如何发送。这不仅涉及内容本身的格式,还包括它被“写入”输出流的机制。现在很多时候POST是按块写入的。如果您查看Apache的HTTPClient源代码,就会看到它如何写入这些块。

由于内容长度的增加是通过一个小数字来标识块和一串随机的小字符序列来分隔每个块写入流中,因此会出现一些问题。可以查看较新版本Java中HTTPURLConnection描述的其他方法。

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接