gpt4 book ai didi

c# - 使用 HttpWebRequest 时保持 session

转载 作者:太空狗 更新时间:2023-10-29 18:04:11 25 4
gpt4 key购买 nike

在我的项目中,我使用 C# 应用程序客户端和 tomcat6 网络应用程序服务器。我在 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;
}
}

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

最佳答案

您必须使用 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;
}
}

关于c# - 使用 HttpWebRequest 时保持 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6275616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com