Calling a servlet from another servlet
I have two servlets that are running on different tomcat servers.
I and am trying to call servlet1 from servlet2 as follows and wanted to write an object to the output stream.
URL url=new URL("http://msyserver/abc/servlet1");
URLConnection con=url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
OutputStream os=con.getOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(os);
oos.writeObject(pushEmailDTO);
oos.flush();
oos.close();
The problem is I can't get into the servlet? I cannot figure out what is missing.
a source to share
I can't ignore it, but it worked by adding the following line to the code.
con.getExpiration();
like this
URL url=new URL("http://msyserver/abc/servlet1");
URLConnection con=url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.getExpiration();//<----------
OutputStream os=con.getOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(os);
oos.writeObject(pushEmailDTO);
oos.flush();
oos.close();
a source to share
Before you can read / send data, you must create a connection via url.connect()
. This is counterintuitive, as the name openConnection()
suggests he does it already, but the docs say:
In general, making a connection to a URL is a multi-step process:
openConnection()
- Manipulate parameters that affect the connection to a remote resource.
- connections ()
- Interaction with a resource; request header fields and content.
That's why it getExpiration()
makes it work: it calls connect()
for you.
a source to share
What error are you getting? Check if the address is correct. If the remote server is running on a port other than 80, consider this when creating the URL.
Also I can suggest HttpClient instead of URLConnection.
a source to share