【问题标题】:Sending a large data by Post between servlets [duplicate]在servlet之间通过Post发送大数据[重复]
【发布时间】:2016-03-28 20:21:03
【问题描述】:

我做了这个实现来向我的 servlet 发送一条 Post 消息:

String urlParameters  = "my_file="+LargeString;
            byte[] postData       = urlParameters.getBytes(StandardCharsets.UTF_8);
            int    postDataLength = postData.length;
            String req        = "http://localhost:8080/MyServlet1";
            URL    url            = new URL( req );
            HttpURLConnection conn= (HttpURLConnection) url.openConnection();           
            conn.setDoOutput( true );
            conn.setInstanceFollowRedirects( false );
            conn.setRequestMethod( "POST" );
            conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); 
            conn.setRequestProperty( "charset", "utf-8");
            conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
            conn.setUseCaches( false );
            try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
                wr.write( postData );
            }

在 myServlet1 中,我尝试使用以下方法检索此数据:

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String mydata_serialized = request.getParameter("my_file");
            System.out.println(mydata_serialized);
}

什么都没有发生。即使我在doPost 中打印一条简单的消息,例如System.out.println("Hello");,也不会发生任何事情。这证明消息没有发送到doPost

请问我怎样才能找回发送的消息?

【问题讨论】:

    标签: java servlets httpurlconnection


    【解决方案1】:

    request.getParameter("my_file") 将查看 URL 本身以挑选 URL 参数。查找 my_file.. 的值,不在请求正文中。

    所以你也许可以利用 request 属性并将其存储在那里..在 POST 消息中做:

    connection.setRequestProperty(key, value);
    

    然后在 doPost() 中将其拉回..

    request.getRequestProperty(key);
    

    或者我认为...如果您保留第一个代码集并使用

    BufferedReader reader = request.getReader();
    

    拉出正文(您将 postData 的值放在它出现的请求正文中。所以您必须查看 doPost() Servlet 上的正文以将信息拉回。网址字符串

    【讨论】:

      猜你喜欢
      • 2014-04-12
      • 1970-01-01
      • 2014-09-15
      • 1970-01-01
      • 1970-01-01
      • 2011-03-23
      • 2020-12-27
      • 1970-01-01
      • 2011-03-03
      相关资源
      最近更新 更多