【问题标题】:Writing post data from one java servlet to another将发布数据从一个 java servlet 写入另一个
【发布时间】:2008-09-18 20:06:30
【问题描述】:

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

【问题讨论】:

    标签: java servlets


    【解决方案1】:

    使用像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】:

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

      【讨论】:

        【解决方案3】:

        HTTP 后上传流的内容及其机制似乎并非您所期望的那样。你不能只写一个文件作为帖子内容,因为 POST 有非常具体的 RFC 标准,说明 POST 请求中包含的数据应该如何发送。它不仅是内容本身的格式,也是如何将其“写入”到输出流的机制。很多时候 POST 现在是分块写入的。如果您查看 Apache 的 HTTPClient 的源代码,您会看到它是如何编写块的。

        结果内容长度有一些怪癖,因为内容长度增加了一个小数字,标识块和一个随机的小字符序列,当它被写入流时,它分隔每个块。查看较新的 Java 版本的 HTTPURLConnection 中描述的其他一些方法。

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

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

        【讨论】:

          【解决方案4】:

          别忘了使用:

          connection.setDoOutput( true)
          

          如果您打算发送输出。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-09-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-09-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多