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

时间:2020-03-06 14:23:16  来源:igfitidea点击:

我正在尝试编写一个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。

解决方案

不要忘记使用:

connection.setDoOutput( true)

如果我们打算发送输出。

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

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

HTTP帖子上传流的内容及其机制似乎并不是我们期望的那样。我们不能仅将文件写为帖子内容,因为POST对于应如何发送POST请求中包含的数据具有非常特定的RFC标准。它不仅是内容本身的格式,而且还是将其"写入"到输出流的机制。现在,很多时间POST都以大块写入。如果查看Apache HTTPClient的源代码,我们将看到它如何编写块。

由于内容长度增加了一个很小的数字(标识该块),并且随机的小字符序列(在每个块写入流中时界定了每个块的边界),因此存在内容长度的怪癖。查看更新的Java版本的HTTPURLConnection中描述的其他方法。

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

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