views:

873

answers:

5

I have two servlets which are running on different tomcat servers.

I and trying to call a servlet1 from servlet2 in the following way and wanted to write an object to 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 that i am unable to hit the servlet? I cannot figure out what i am missing.

+1  A: 

What is the error you are getting? Check that the address is correct. If the remote server is running in a port other than 80, then take this into consideration when building the URL.

May also I suggest to use HttpClient instead of URLConnection.

kgiannakakis
I am not getting any exception every line executes successfully. Also the servlet is running on the exact url that i am passing in the code mentioned.
Abdul Khaliq
+1  A: 

I cannot unserstand but it worked by adding the following line in 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();
Abdul Khaliq
A: 

Why not replace your communication with rmi?

mP
well i need to communicate over the web? how will i use rmi to communicate over the web.
Abdul Khaliq
+4  A: 

You must create a connection via url.connect() before you can read/send data. This is counter-intuitive since the name openConnection() suggests that it does that already but the docs say:

In general, creating a connection to a URL is a multistep process:

  1. openConnection()
  2. Manipulate parameters that affect the connection to the remote resource.
  3. connect()
  4. Interact with the resource; query header fields and contents.

This is why getExpiration() makes it work: It calls connect() for you.

Aaron Digulla
A: 

" cannot unserstand but it worked by adding the following line in the code "

con.getExpiration();

Thanx Abdul it also worked for me!!! What is the reason behind it!!!!

sanjeev sharma
URLConnection is lazily loaded. The *request* will **ONLY** be sent if you ask information about the *response*. Normal practice is to do `connection.getInputStream().close()` in the last code line.
BalusC