Reputation: 2463
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.
Upvotes: 2
Views: 4615
Reputation: 2463
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();
Upvotes: 1
Reputation: 328790
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:
openConnection()
- Manipulate parameters that affect the connection to the remote resource.
- connect()
- Interact with the resource; query header fields and contents.
This is why getExpiration()
makes it work: It calls connect()
for you.
Upvotes: 6
Reputation: 104198
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.
Upvotes: 1