Preface
Recently, the company used the HttpClient object to send requests and abandoned the previous HttpWebRequest. There is an advantage to using httpClient: it is that it can only use one instance of HttpClient to complete the sending of all request data (address, request data, type, cookies, etc.).
The traditional HttpWebRequest needs to create a separate instance for each request, and avoids an old problem: the problem of untimely release of Socket connections.
The following is a post forwarding of other fellow Taoists. The main reason is that during the use process, you need to send a custom cookie to the target server, but you can't send it over. Finally, the articles of other fellow Taoists on Baidu found that if you need to send your own cookies, you need to make a setting:
var handler = new HttpClientHandler() { UseCookies = false}; var client = new HttpClient(handler);// { BaseAddress = baseAddress };
There are generally two ways
The first type
=true (default is true), by default, you will bring cookies yourself
For example:
var handler = new HttpClientHandler() { UseCookies = true }; var client = new HttpClient(handler);// { BaseAddress = baseAddress }; ("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0"); ("Connection", "Keep-Alive"); ("Keep-Alive", "timeout=600"); var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("email", "xxxx"), new KeyValuePair<string, string>("password", "xxxx"), }); var result = await ("/cp/login", content); ();
In this case, after the post request login is successful, it will redirect to another page and will automatically bring cookies.
If set to false, redirect after logging in will not automatically bring cookies, and it will jump to the login page.
The second type
When setting = false, you need to manually add cookies to headers.
var handler = new HttpClientHandler() { UseCookies = false}; var client = new HttpClient(handler);// { BaseAddress = baseAddress }; var message = new HttpRequestMessage(, url); ("Cookie", "session_id=7258abbd1544b6c530a9f406d3e600239bd788fb"); var result = await (message); ();
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.