>问题:我正在尝试使用httpclient从站点获取数据。现在,该网站要求您首先访问一个链接,然后只有您可以将数据发布到下一个链接。链接 1 是一个简单的获取请求链接 2 是一个发布请求现在我认为该站点首先存储来自link1的一些cookie,然后仅允许您将数据发布到link2,因为每当我尝试以隐身方式打开link2时,该站点都会显示错误消息"会话超时或达到最大连接限制。无法继续。请关闭并重新启动浏览器" 现在我已经尝试了这个:
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();
}
但是我收到会话超时错误消息。如何维护从网络持续接收的 httpClient 会话的 Cookie。就像在python中一样,它可以通过以下方式完成
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
urllib2.install_opener(opener)
链接1
链接2
CookieContainer
为您处理 Cookie。
这样做,您将像这样创建HttpClient。
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));
(请注意,它使用 System.Net.Http 中的 HttpClient 版本)
因此,在第一次响应后,您有Set-Cookie
标头:
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);
}
之后,只需将您的 cookie 设置为请求消息:
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);