Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping a session when using HttpWebRequest

In my project I'm using C# app client and tomcat6 web application server. I wrote this snippet in the C# client:

public bool isServerOnline()
{
        Boolean ret = false;

        try
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(VPMacro.MacroUploader.SERVER_URL);
            req.Method = "HEAD";
            req.KeepAlive = false;
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            if (resp.StatusCode == HttpStatusCode.OK)
            {
                // HTTP = 200 - Internet connection available, server online
                ret = true;
            }
            resp.Close();
            return ret;

        }
        catch (WebException we)
        {
            // Exception - connection not available
            Log.e("InternetUtils - isServerOnline - " + we.Status);
            return false;
        }
}

Everytime I invoke this method, I get a new session at server side. I suppose it's because I should use HTTP cookies in my client. But I don't know how to do that, can you help me?

like image 376
CeccoCQ Avatar asked Jun 08 '11 07:06

CeccoCQ


1 Answers

You must use a CookieContainer and keep the instance between calls.

private CookieContainer cookieContainer = new CookieContainer();
public bool isServerOnline()
{
        Boolean ret = false;

        try
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(VPMacro.MacroUploader.SERVER_URL);
            req.CookieContainer = cookieContainer; // <= HERE
            req.Method = "HEAD";
            req.KeepAlive = false;
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            if (resp.StatusCode == HttpStatusCode.OK)
            {
                // HTTP = 200 - Internet connection available, server online
                ret = true;
            }
            resp.Close();
            return ret;

        }
        catch (WebException we)
        {
            // Exception - connection not available
            Log.e("InternetUtils - isServerOnline - " + we.Status);
            return false;
        }
}
like image 83
Guillaume Avatar answered Oct 11 '22 13:10

Guillaume