问题描述:

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

网友答案:

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)

网友答案:

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);
相关阅读:
Top