C# Httpclient编程
生活随笔
收集整理的這篇文章主要介紹了
C# Httpclient编程
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
今天研究了一天C#如何添加cookie到httpcient里面,從而發(fā)請(qǐng)求時(shí),能把cookie作為頭部發(fā)出,最后發(fā)現(xiàn)根本加不進(jìn)去。
Httpclient的cookie是來(lái)自上一個(gè)請(qǐng)求的響應(yīng),httpclient會(huì)自動(dòng)把上一個(gè)請(qǐng)求的響應(yīng)里面的cookie保存起來(lái),所以當(dāng)發(fā)送幾個(gè)有關(guān)聯(lián)的request,就必須要用同一個(gè)Httpclient
示例:
//第一個(gè)請(qǐng)求HttpClient client = new HttpClient();// 為JSON格式添加一個(gè)Accept報(bào)頭//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(';'));}}}//第二個(gè)請(qǐng)求,在這個(gè)請(qǐng)求里,沒(méi)有設(shè)置cookie,由于跟第一個(gè)請(qǐng)求使用相同httpclient,所以cookie會(huì)自動(dòng)放入請(qǐng)求頭部發(fā)給服務(wù)器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;}}頂
?
轉(zhuǎn)載于:https://www.cnblogs.com/shiningrise/p/5931362.html
與50位技術(shù)專家面對(duì)面20年技術(shù)見(jiàn)證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的C# Httpclient编程的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 我为了不睡觉+这个已经是第四杯奶茶怎么回
- 下一篇: 要多少钱可以加盟大江美蛙鱼火锅,加盟效果