gpt4 book ai didi

c# - WebClient中如何获取Cookie的JSESSIONID

转载 作者:太空狗 更新时间:2023-10-29 21:08:30 28 4
gpt4 key购买 nike

我已经实现了以下方法来从 Cookies 中获取 JsessioniD。网站使用表单例份验证。

这是我实现的。

public override void ViewDidLoad ()
{
base.ViewDidLoad ();
using(var client= new CookieAwareWebClient())
{
var values= new NameValueCollection
{
{"username","admin"},
{"password","admin"},
};
client.UploadValues("myURL/j_security_check",values);
WebHeaderCollection myWebHeaderCollection = client.ResponseHeaders;

for (int i=0; i < myWebHeaderCollection.Count; i++)
Console.WriteLine ("\t" + myWebHeaderCollection.GetKey(i) + " = " + myWebHeaderCollection.Get(i));
};
}

CookieAwareWebClient类实现如下:

public class CookieAwareWebClient : WebClient
{

public CookieAwareWebClient()
{
CookieContainer = new CookieContainer();
}

public CookieContainer CookieContainer { get; private set; }

protected override WebRequest GetWebRequest(Uri address)
{
var request = (HttpWebRequest)base.GetWebRequest(address);
request.CookieContainer = CookieContainer;
return request;
}
}

enter image description here

我的问题是如何只获取JsessionID?

最佳答案

您可以将响应 cookie 存储在单独的属性中:

public class CookieAwareWebClient : WebClient
{
public CookieAwareWebClient()
{
CookieContainer = new CookieContainer();
this.ResponseCookies = new CookieCollection();
}

public CookieContainer CookieContainer { get; private set; }
public CookieCollection ResponseCookies { get; set; }

protected override WebRequest GetWebRequest(Uri address)
{
var request = (HttpWebRequest)base.GetWebRequest(address);
request.CookieContainer = CookieContainer;
return request;
}

protected override WebResponse GetWebResponse(WebRequest request)
{
var response = (HttpWebResponse)base.GetWebResponse(request);
this.ResponseCookies = response.Cookies;
return response;
}
}

然后:

client.UploadValues("myURL/j_security_check",values);
Cookie jSessionID = client.ResponseCookies["JSESSIONID"];
if (jSessionID != null)
{
// The server set a cookie called JSESSIONID, you can use it here:
string value = jSessionID.Value;
}

关于c# - WebClient中如何获取Cookie的JSESSIONID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29479149/

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