使用HttpWebRequest时保持会话

时间:2011-06-08 07:38:55

标签: c# httpwebrequest session-cookies

在我的项目中,我正在使用C#app客户端和tomcat6 Web应用程序服务器。 我在C#客户端编写了这个代码片段:

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

每次我调用此方法时,我都会在服务器端获得一个新会话。 我想这是因为我应该在我的客户端使用HTTP cookie。但我不知道该怎么做,你能帮助我吗?

1 个答案:

答案 0 :(得分:25)

您必须使用CookieContainer并在调用之间保留实例。

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