Keeping a session when using HttpWebRequest

2020-07-06 08:14发布

问题:

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?

回答1:

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;
        }
}