Uwpbeginner
Uwpbeginner

Reputation: 405

Httpclient Cookie Issue

Issue: I am trying to use httpclient for fetching data from a site.Now the site requires you to first visit a link then only you can post data to the next link. Link1 is a simple get request Link2 is a post request Now I think the site first store some cookie from the link1 and then only allow you to post data to link2 as whenever I try to open the link2 in incognito the site displays the error message "Session Timed out OR Maximum connections limit reached. Cannot Proceed Further. Please close and restart your browser " Now I have tried this:

 try
        {
            //Send the GET request
            httpResponse = await httpClient.GetAsync(new Uri(link1UriString));
            //Send the POSTrequest
             httpResponse = await httpClient.PostAsync(new Uri(link2uriString),postContent);                
            httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

            }

But I am getting the session timed out error message. How to maintain cookies for a session in httpClient continuously received from the web.Like in python it can be done by

 opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
 urllib2.install_opener(opener)

Link1
Link2

Upvotes: 3

Views: 2102

Answers (2)

Andrii Krupka
Andrii Krupka

Reputation: 4306

So, after first response you have Set-Cookie header:

var responseMessage = await httpClient.GetAsync("http://115.248.50.60/registration/Main.jsp?wispId=1&nasId=00:15:17:c8:09:b1");
IEnumerable<string> values;
var coockieHeader = string.Empty;
if (responseMessage.Headers.TryGetValues("set-cookie", out values))
{
    coockieHeader = string.Join(string.Empty, values);
}

After that, just setup your cookie into request message:

        var httpRequestMessage = new HttpRequestMessage
        {
            RequestUri = new Uri("http://115.248.50.60/registration/chooseAuth.do"),
            Content = postContent,
            Method = HttpMethod.Post
        };

        httpRequestMessage.Headers.Add("Cookie", values);
        var httpResponse = await httpClient.SendAsync(httpRequestMessage);

Upvotes: 1

Matt Lacey
Matt Lacey

Reputation: 65564

You can use a CookieContainer to handle cookies for you.
Doing so, you'd create the HttpClient like this.

using System.Net;
using System.Net.Http;

CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
HttpClient httpClient = new HttpClient(handler);

httpResponse = await httpClient.GetAsync(new Uri(link1UriString));

(Note it uses the version of HttpClient in System.Net.Http)

Upvotes: 3

Related Questions