WebClient中如何获取Cookie的JSESSIONID

How to Get Cookie JSESSIONID in WebClient

我已经实现了以下方法来从 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));
        };
    }

CookieAwareWebClientClass实现如下:

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

我的问题是如何只获取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;
}

根据以下文章,也可以将以下代码用于 HttpRequest:https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.cookiecontainer%28v=vs.110%29.aspx

private void FindCookie ()
        {
            HttpWebRequest request = WebRequest.Create (addyourURL) as HttpWebRequest;
            request.CookieContainer = new CookieContainer ();    
            // Set the Method property of the request to POST.
            request.Method = "POST";
            // Create POST data and convert it to a byte array.
            string postData = "loginForm=loginForm&j_username=admin&j_password=admin";
            byte[] byteArray = Encoding.UTF8.GetBytes (postData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;
            // Get the request stream.
            Stream dataStream = request.GetRequestStream ();
            // Write the data to the request stream.
            dataStream.Write (byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close ();
            // Get the response.
            HttpWebResponse response = request.GetResponse () as HttpWebResponse;
            // Display the status.
            Console.WriteLine (((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream ();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader (dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd ();
            // Display the content.
            Console.WriteLine (responseFromServer);
            // Clean up the streams.
            reader.Close ();
            dataStream.Close ();
            response.Close ();

            string sid = response.Cookies["JSESSIONID"].ToString();

            Console.WriteLine(sid);
}

仅针对异步操作修改了 class:

public class CookieAwareWebClient : WebClient
{
    public string ResponseCookies { get; private set; }

    protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
    {
        var response = base.GetWebResponse(request, result);
        this.ResponseCookies = response.Headers["Set-Cookie"];
        return response;
    }
}