Question

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.

Was it helpful?

Solution 3

I cannot unnderstand 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();

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top