如何在WebClient中获取Cookie JSESSIONID

时间:2015-04-06 20:30:28

标签: c# authentication xamarin

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

这是我实施的内容。

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?

3 个答案:

答案 0 :(得分:10)

您可以将响应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;
}

答案 1 :(得分:0)

以下代码将根据以下文章用于Http请求: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);
}

答案 2 :(得分:0)

修改后的类仅用于异步操作:

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