2

I would like to call a servlet from another servlet doing two things:

  1. setting the content type to "multipart/form-data"
  2. setting the method to "POST".

This is very easy to do from a form, but I need to do it from another servlet. Any ideas how?

bluish
  • 26,356
  • 27
  • 122
  • 180
fernandohur
  • 7,014
  • 11
  • 48
  • 86

3 Answers3

3

You can use java.net.HttpUrlConnection or maybe Apache HTTP client to send a POST/GET request to the other servlet. You will basically be invoking the other servlet the same way a browser would.

bluish
  • 26,356
  • 27
  • 122
  • 180
jeff
  • 4,325
  • 16
  • 27
  • HttpClient works perfect, thank you. Although I do have one question, how do you set the content type? – fernandohur Oct 15 '11 at 01:30
  • I'm not terribly familiar with HttpClient but check out addRequestHeader in HttpMethod. I think you can specify your content-type with that. – jeff Oct 15 '11 at 01:37
1

It sounds like request forwarding or include is what you're looking for. What you actually do will depend on what you intend to do with the output of the target servlet. Are you going to display it somehow? Or are you simply discarding it? You may in some cases, need to be a bit more "creative" in how you invoke those methods (e.g., either creating your own request/response instances, or wrapping the current request/response so that state changes are isolated).

Alternatively, to keep things simple you may want to just open a network connection to your target servlet's mapped URL as Jeff suggested.

Community
  • 1
  • 1
Jack Leow
  • 21,945
  • 4
  • 50
  • 55
  • You cannot change the incoming request, wrapping would not make much sense. You really have to create a brand new request. I have however the impression that OP is looking in the wrong corner for the solution to his concrete problem (which he didn't tell anything about, so suggesting the right solution is impossible). – BalusC Oct 15 '11 at 00:47
0

It sounds like you want to send an HTTP POST with java. I would recommend using apache HttpClient. Check out this question Add parameters to Apache HttpPost

You can also do this with pure java with (HttpUrlConnection)[ http://download.oracle.com/javase/6/docs/api/java/net/HttpURLConnection.html].

Community
  • 1
  • 1
Jon7
  • 7,165
  • 2
  • 33
  • 39