Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using a servlet to initiate a request

 
Steve Watson
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can I have a servlet initiate a request? In otherwords construct the HTTP request and send it to another URL.
Steve Watson
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13061
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should look in the java.net package - the URLConnection and HttpURLConnection classes. The JavaDocs are pretty informative.
Bill
 
Geeta Ramasami
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Use something like this:
URL url = new URL();
URLConnection UrlConnObj1 = url1.openConnection();
HttpURLConnection huc1 = (HttpURLConnection)UrlConnObj1;
huc1.setRequestMethod("POST");
huc1.setRequestProperty("Cookie",firstcookie);
huc1.setDoOutput(true);
huc1.setDoInput(true);
huc1.setUseCaches(false);
huc1.setDefaultUseCaches(false);
huc1.setRequestProperty("Content-type","application/x-www-
form-urlencoded");
Try if this works..
Cheers
Geets
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13061
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that you will only get a HttpURLConnection if the URL is the http type - for example constucted with "http://someserver/someapp"
Bill
 
Gary McGath
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This works only if URL.openConnection returns java.net.HttpURLConnection; it isn't guaranteed that it will be, even if the URL is an HTTP type. To make it work reliably across all browsers (in particular, the implementation by a certain company in Washington state, at least on some versions of IE), you need to catch an exception when doing the class cast. You can still proceed, but you don't have access to setRequestMethod, which means that you must proceed with a GET request. Very annoying.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13061
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gary - which Java implementation does not return a HttpURLConnection?
Bill
 
Dasun Perera
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By any chance if this URL you want to contact is in the same server you can use javax.servlet.RequestDispatcher to handle the situation easily. BUt if this URL is ourside the server as our friends mentioned you need to use URLConnection class
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic