当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《将发布数据从一个javaservlet写入另一个》经验,为你挑选了2个好方法。

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



1> Peter Hilton..:

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



2> Sietse..:

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

推荐阅读
吻过彩虹的脸_378
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有