1

Possible Duplicate:
communication between remote servlets

Is it possible to send objects between servlets on different servers? The issue is, when my servlet receives a http request, before sending a response, it would need to send some data to another web application (on different server), get a response, and then process the received data. However I don't really know how to tackle the problem. Is it possible for a servlet to send a http request to another servlet, and then get the response from it?

Community
  • 1
  • 1
Kamil
  • 13
  • 3

2 Answers2

0

Of course it is possible - you can create an HttpURLConnection in it in the same way you would do it from JavaSE. Usually what I do is, in case of an error, to forward to the client the original (second server) HTTP error code.

thedayofcondor
  • 3,860
  • 1
  • 19
  • 28
0

Here's an example of how to use HttpURLConnection to communicate with another servlet (or any http server)...

URL url = new URL ("http://host/myservlet");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput (true);
connection.setDoInput (true);
OutputStream os = connection.getOutputStream();
//TODO: optionally, send something through the OutputStream to your servlet
os.flush();
os.close();
InputStream is = connection.getInputStream();
//TODO: retrieve your results from the InputStream
is.close();

Be sure to close your streams when done or use try-with-resources blocks. You can use ObjectInputStream or InputStreamReader based on your needs. You can also use the setRequestProperty method of the HttpURLConnection to define things such as the user-agent or cookies if needed.

cmevoli
  • 351
  • 2
  • 6