aspose file tools*
The moose likes Servlets and the fly likes Using a servlet to initiate a request Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Using a servlet to initiate a request" Watch "Using a servlet to initiate a request" New topic
Author

Using a servlet to initiate a request

Steve Watson
Ranch Hand

Joined: Apr 08, 2003
Posts: 38
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

Joined: Mar 22, 2000
Posts: 12789
    
    5
You should look in the java.net package - the URLConnection and HttpURLConnection classes. The JavaDocs are pretty informative.
Bill
Geeta Ramasami
Ranch Hand

Joined: Mar 05, 2003
Posts: 72
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

Joined: Mar 22, 2000
Posts: 12789
    
    5
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

Joined: Mar 15, 2003
Posts: 52
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.


http://www.mcgath.com/consulting/
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12789
    
    5
Gary - which Java implementation does not return a HttpURLConnection?
Bill
Dasun Perera
Greenhorn

Joined: Jul 09, 2002
Posts: 13
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Using a servlet to initiate a request