2008-09-18 74 views
9

我想写一个servlet,它将通过POST将XML文件(xml格式的字符串)发送到另一个servlet。 (非必需的XML生成代码替换为“你好”)从一个java servlet写入数据到另一个

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) 

回答

13

使用类似HttpClient这样的库,这种事情要容易得多。甚至还有一个post XML code example

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); 
2

不要忘记使用。

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

的HTTP POST上载流的内容和它的力学似乎并没有成为你期待什么他们是。您不能仅仅将文件写为发布内容,因为POST具有非常特定的RFC标准,用于说明POST请求中包含的数据应如何发送。它不仅仅是内容本身的格式化,它也是它如何“写入”输出流的机制。现在很多时候POST都是以块的形式写入的。如果您查看Apache HTTPClient的源代码,您将看到它如何写入块。

由于内容长度增加了少量数字,因此内容长度会增加,从而识别组块和一个随机分配每个组块的随机小字符序列,因为它会写入流中。查看HTTPURLConnection的较新Java版本中描述的一些其他方法。

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

如果你不知道你在做什么,也不想了解它,处理将像Apache了HTTPClient的依赖性确实最终会被容易得多,因为它抽象所有的复杂性和只是工作。

相关问题