Today, I studied how C # adds cookies to the httpcient, so that when you send a request, you can send the cookie as the head and finally find that it doesn't add up.
A httpclient cookie is a response from the previous request, and HttpClient automatically saves the cookie in the response to the previous request, so when you send several associated requests, you must use the same httpclient
Example:
First request
httpclient client = new HttpClient ();
//Add a accept header to the JSON format
//client. DEFAULTREQUESTHEADERS.ACCEPT.ADD (
// new Mediatypewithqualityheadervalue ("Application/json"));
String strdecodebody = Httputility.urlencode (strbody);
httpcontent content = new Stringcontent ( Strdecodebody);
content. Headers.contenttype = new Mediatypeheadervalue ("Application/json");
Client. Defaultrequestheaders.add ("User-agent", "mozilla/5.0");
Client. Defaultrequestheaders.add ("Authentication", "123");
Httpresponsemessage response = null;
Response = client. Postasync (StrIP, content). result;
if (response!= null)
{
if (Expectcode = = Httpstatuscode.ok)
{
var resultvalue = response. Content.readasstringasync (). result;
String strresponse = Httputility.urldecode (resultvalue.tostring ());
String[] Strcookies = (string[]) response. Headers.getvalues ("Set-cookie");
if (strcookies.length>0)
{
Strcookie = Strcookies[0]. Substring (0, Strcookies[0]. IndexOf (';'));
}
}
}
The second request, in which the cookie is not set, is automatically placed in the request header and sent to the server because the same httpclient is used with the first request.
String strencodebody = Httputility.urlencode (strbody);
Httpcontent content = new Stringcontent (strencodebody);
Content. Headers.contenttype = new Mediatypeheadervalue ("Application/json");
Httpresponsemessage response = null;
Response = client. Postasync (StrIP, content). result;
if (response!= null)
{
if (Expectcode = = Httpstatuscode.ok)
{
var resultvalue = response. Content.readasstringasync (). result;
String strresponse = Httputility.urldecode (resultvalue.tostring ());
return strresponse;
}
}