Calling a Servlet Message from Another Servlet

I need to call the POST method of the servlet from another servlet and pass the blob in the parameters of the servlet. Is this possible, if so, how can this be done. PS: I can not use Apache HttpClient

+6
source share
3 answers

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

As the HttpClient (and another third-party library?) Is apparently not an option, it is best to use the standard Java SE API provided by java.net.URLConnection . In short: Using java.net.URLConnection to start and process HTTP requests Below you can find an example of multipart/form-data .

Please note that this problem does not apply to servlets. In other words, you should be able to execute this code in a simple Java application using the main() method. This simplifies testing and finalization. Once you earn it, just let the servlet execute the same piece of code.


Not related to the problem, I got the impression that somewhere there was a serious design failure, of course, if both servlets work in the same context of web applications. The other servlet that you want to send the POST request to is apparently too tightly coupled and needs to be reorganized.

+8
source

You can send the dispatcher to another servlet in your application and forward it or enable it, as @Ryan suggests. The code should be approximately the same in your first servlet:

 ServletContext context = this.getServletContext(); RequestDispatcher dispatcher = context.getRequestDispatcher("/otherurltoservlet"); // change your request and response accordingly dispatcher.forward(request, response); 
+7
source

Do you mean a call from your application to another web service? If so, then something like HttpClient is what you want. If you mean that you want to programmatically call another servlet in your application, then you are looking to either forward it or enable it .

+1
source

Source: https://habr.com/ru/post/899378/


All Articles