且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从另一个Servlet调用Servlet Post

更新时间:2023-12-04 14:41:22

您需要自己创建并发送HTTP请求。您无法使用forward / redirect / include,因为您想要将方法从GET更改为POST,并且您想要发送 multipart / form-data 请求。

You need to create and send a HTTP request yourself. You cannot make use of forward/redirect/include because you want to change the method from GET to POST and you want to send a multipart/form-data request.

由于HttpClient(和其他第三方库?)显然不是一个选项,***的办法是使用提供的标准Java SE API java.net.URLConnection 。长话短说:使用java.net .URLConnection以触发和处理HTTP请求在底部,您可以找到 multipart / form-data 示例。

As HttpClient (and other 3rd party library?) is apparently not an option, your best bet is to use the standard Java SE API provided java.net.URLConnection. Long story short: Using java.net.URLConnection to fire and handle HTTP requests At the bottom you can find a multipart/form-data example.

请注意,此问题并非特定于servlet。换句话说,您必须能够使用 main()方法在普通的Java应用程序中执行此代码。这样可以更轻松地进行测试和微调。一旦你开始工作,只需让servlet执行相同的代码。

Please note that this problem is not specific to servlets. In other words, you must be able to execute this code in a plain vanilla Java application with a main() method. This allows for easier testing and finetuning. Once you get it to work, just let the servlet execute the same piece of code.

不相关对于这个问题,我的印象是某个地方存在重大设计失败,当然,如果两个servlet都在同一个Web应用程序上下文中运行。您想要发送POST请求的另一个servlet显然过于紧密耦合,应该重构。

Unrelated to the problem, I have the impression that there's a major design failure somewhere, certainly if the both servlets runs in the same webapplication context. The other servlet where you want to send the POST request to is apparently too tight coupled and should be refactored.