jQuery in Action, 3rd edition
The moose likes Sockets and Internet Protocols and the fly likes client request  to server using  HttpURLConnection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Bookmark "client request  to server using  HttpURLConnection" Watch "client request  to server using  HttpURLConnection" New topic

client request to server using HttpURLConnection

Manoj Tare

Joined: Feb 04, 2003
Posts: 26
I'm trying to write a client side java application that will log onto a server. This server I have no control over and thus must interface with it how it wants, which is (as far as I can see) through cookies and redirection. I've tried using the HttpURLConnection class to connect to the server and capture the cookies it sends, but I'm not having any joy. although i can trap the cookies, and to the best of my knowledge return them in subsequent requests, I still get "Temprary cookies must be enabled to access this site" error message. When I connect in a browser, it works fine, so its obviously something I am not doing. I know for a fact upon the first connection the sites sets at least one intial cookie, then on the second connection it sets a further two. both times, afaik it redirects you. The server ha a single ID field that uses the GET method to write to the server, but dispite my best efforts I really cannot figure this one out. If anyone can offer some advice on what I shoudl do, please do! I would appreciate it.
For first page it is connecting but when first page redirects it to second page it couldn't find
session .
URL url = new URL("http://localhost/sample/login.asp");
HttpURLConnection httpcon=null;
try {
httpcon = (HttpURLConnection) url.openConnection();

String cookie = httpcon.getHeaderField("Set-Cookie");
httpcon =(HttpURLConnection) url.openConnection();
httpcon.setRequestProperty("Cookie", cookie);
[ March 04, 2003: Message edited by: Manoj Tare ]
Lance Bader

Joined: Dec 12, 2004
Posts: 2
Your problem is caused by the automatic redirection. The HttpURLConnection, by default, is smart enough to follow the redirection but not smart enough to add the required cookies to the header.

You can use the HttpURLConnection.setInstanceFollowRedirects() method (added in Java 1.3) to stop your connection from following redirections automatically. Then you must use the HttpURLConnection.getResponseCoe() method and check for redirections, extracting the new URL and adding the cookies as necessary.

Alternatively, you can use the HttpClient package from Jakarta (http://jakarta.apache.org/commons/httpclient/) which will perform the cookie management automatically.
I agree. Here's the link: http://aspose.com/file-tools
subject: client request to server using HttpURLConnection
It's not a secret anymore!