使用HttpWebRequest时保持会话 [英] Keeping a session when using HttpWebRequest

查看:84
本文介绍了使用HttpWebRequest时保持会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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?

推荐答案

您必须使用 CookieContainer ,并在两次调用之间保留实例.

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

这篇关于使用HttpWebRequest时保持会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆