這篇文章主要介紹了C# .net core實(shí)現(xiàn)的網(wǎng)絡(luò)請(qǐng)求方法,大致介紹下在.net core 下如何進(jìn)行http請(qǐng)求,主要仍然是GET和POST方法,示例代碼介紹的非常詳細(xì),非常適合初學(xué)者入門(mén)。
公司主營(yíng)業(yè)務(wù):成都做網(wǎng)站、網(wǎng)站設(shè)計(jì)、外貿(mào)營(yíng)銷(xiāo)網(wǎng)站建設(shè)、移動(dòng)網(wǎng)站開(kāi)發(fā)等業(yè)務(wù)。幫助企業(yè)客戶(hù)真正實(shí)現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競(jìng)爭(zhēng)能力。成都創(chuàng)新互聯(lián)是一支青春激揚(yáng)、勤奮敬業(yè)、活力青春激揚(yáng)、勤奮敬業(yè)、活力澎湃、和諧高效的團(tuán)隊(duì)。公司秉承以“開(kāi)放、自由、嚴(yán)謹(jǐn)、自律”為核心的企業(yè)文化,感謝他們對(duì)我們的高要求,感謝他們從不同領(lǐng)域給我們帶來(lái)的挑戰(zhàn),讓我們激情的團(tuán)隊(duì)有機(jī)會(huì)用頭腦與智慧不斷的給客戶(hù)帶來(lái)驚喜。成都創(chuàng)新互聯(lián)推出孟村免費(fèi)做網(wǎng)站回饋大家。
本文章是在VS2017的環(huán)境下,.net core 1.1版本以上。
在這期間,由于.net core 并不基于IIS,我們的過(guò)去的網(wǎng)絡(luò)請(qǐng)求代碼在.net core框架下,有可能會(huì)出現(xiàn)不兼容,報(bào)錯(cuò)的現(xiàn)象。這里大致介紹下在.net core 下如何進(jìn)行http請(qǐng)求,主要仍然是GET和POST方法,有錯(cuò)誤的地方,歡迎指正!
先來(lái)說(shuō)POST,POST我實(shí)現(xiàn)了三種方法,前兩種基于的原理是完全一致的,后面的有些小小的差異,但他們的本質(zhì)都是http請(qǐng)求,本質(zhì)上是無(wú)區(qū)別的,只是實(shí)現(xiàn)方法有所不同。
廢話不多說(shuō),上代碼:
POST異步方法:
////// 異步請(qǐng)求post(鍵值對(duì)形式,可等待的) /// /// 網(wǎng)絡(luò)基址("http://localhost:59315") /// 網(wǎng)絡(luò)的地址("/api/UMeng") /// 鍵值對(duì)List> formData = new List >();formData.Add(new KeyValuePair ("userid", "29122"));formData.Add(new KeyValuePair ("umengids", "29122")); /// 編碼格式 /// 頭媒體類(lèi)型 /// public async Task HttpPostAsync(string uri, string url, List > formData = null, string charset = "UTF-8", string mediaType = "application/x-www-form-urlencoded") { string tokenUri = url; var client = new HttpClient(); client.BaseAddress = new Uri(uri); HttpContent content = new FormUrlEncodedContent(formData); content.Headers.ContentType = new MediaTypeHeaderValue(mediaType); content.Headers.ContentType.CharSet = charset; for (int i = 0; i < formData.Count; i++) { content.Headers.Add(formData[i].Key, formData[i].Value); } HttpResponseMessage resp = await client.PostAsync(tokenUri, content); resp.EnsureSuccessStatusCode(); string token = await resp.Content.ReadAsStringAsync(); return token; }
POST同步方法:
////// 同步請(qǐng)求post(鍵值對(duì)形式) /// /// 網(wǎng)絡(luò)基址("http://localhost:59315") /// 網(wǎng)絡(luò)的地址("/api/UMeng") /// 鍵值對(duì)List> formData = new List >();formData.Add(new KeyValuePair ("userid", "29122"));formData.Add(new KeyValuePair ("umengids", "29122")); /// 編碼格式 /// 頭媒體類(lèi)型 /// public string HttpPost(string uri, string url, List > formData = null, string charset = "UTF-8", string mediaType = "application/x-www-form-urlencoded") { string tokenUri = url; var client = new HttpClient(); client.BaseAddress = new Uri(uri); HttpContent content = new FormUrlEncodedContent(formData); content.Headers.ContentType = new MediaTypeHeaderValue(mediaType); content.Headers.ContentType.CharSet = charset; for (int i = 0; i < formData.Count; i++) { content.Headers.Add(formData[i].Key, formData[i].Value); } var res = client.PostAsync(tokenUri, content); res.Wait(); HttpResponseMessage resp = res.Result; var res2 = resp.Content.ReadAsStringAsync(); res2.Wait(); string token = res2.Result; return token; }
遺憾的是,同步方法也是基于異步實(shí)現(xiàn)的,個(gè)人認(rèn)為這樣做會(huì)加大系統(tǒng)開(kāi)銷(xiāo)。如果各位有其他的高效實(shí)現(xiàn),請(qǐng)不吝賜教!
接下來(lái)是通過(guò)流的方式進(jìn)行POST:
public string Post(string url, string data, Encoding encoding, int type) { try { HttpWebRequest req = WebRequest.CreateHttp(new Uri(url)); if (type == 1) { req.ContentType = "application/json;charset=utf-8"; } else if (type == 2) { req.ContentType = "application/xml;charset=utf-8"; } else { req.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; } req.Method = "POST"; //req.Accept = "text/xml,text/javascript"; req.ContinueTimeout = 60000; byte[] postData = encoding.GetBytes(data); Stream reqStream = req.GetRequestStreamAsync().Result; reqStream.Write(postData, 0, postData.Length); reqStream.Dispose(); var rsp = (HttpWebResponse)req.GetResponseAsync().Result; var result = GetResponseAsString(rsp, encoding); return result; } catch (Exception ex) { throw; } }
private string GetResponseAsString(HttpWebResponse rsp, Encoding encoding) { Stream stream = null; StreamReader reader = null; try { // 以字符流的方式讀取HTTP響應(yīng) stream = rsp.GetResponseStream(); reader = new StreamReader(stream, encoding); return reader.ReadToEnd(); } finally { // 釋放資源 if (reader != null) reader.Dispose(); if (stream != null) stream.Dispose(); if (rsp != null) rsp.Dispose(); } }
這種方式的POST還是將數(shù)據(jù)寫(xiě)入到流里面,進(jìn)行POST,之所以寫(xiě)前兩個(gè)key-value的形式,是為了符合java或者oc的風(fēng)格,在c#書(shū)寫(xiě)的webapi中,由于接收形式是{=value}而不是{key=value}(由webapi的性質(zhì)決定),后續(xù)我會(huì)說(shuō)如何在webapi中接收(key-value)的形式,適當(dāng)避免.net后臺(tái)人員與android和ios的矛盾,從而達(dá)到社會(huì)主義民主社會(huì)的長(zhǎng)治久安。
接下來(lái)是get,同樣同步異步都是由異步實(shí)現(xiàn)的,還請(qǐng)各位看官輕噴。
GET:
////// 異步請(qǐng)求get(UTF-8) /// /// 鏈接地址 /// 寫(xiě)在header中的內(nèi)容 ///public static async Task HttpGetAsync(string url, List > formData = null) { HttpClient httpClient = new HttpClient(); HttpContent content = new FormUrlEncodedContent(formData); if (formData != null) { content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); content.Headers.ContentType.CharSet = "UTF-8"; for (int i = 0; i < formData.Count; i++) { content.Headers.Add(formData[i].Key, formData[i].Value); } } var request = new HttpRequestMessage() { RequestUri = new Uri(url), Method = HttpMethod.Get, }; for (int i = 0; i < formData.Count; i++) { request.Headers.Add(formData[i].Key, formData[i].Value); } var resp = await httpClient.SendAsync(request); resp.EnsureSuccessStatusCode(); string token = await resp.Content.ReadAsStringAsync(); return token; }
////// 同步get請(qǐng)求 /// /// 鏈接地址 /// 寫(xiě)在header中的鍵值對(duì) ///public string HttpGet(string url, List > formData = null) { HttpClient httpClient = new HttpClient(); HttpContent content = new FormUrlEncodedContent(formData); if (formData != null) { content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); content.Headers.ContentType.CharSet = "UTF-8"; for (int i = 0; i < formData.Count; i++) { content.Headers.Add(formData[i].Key, formData[i].Value); } } var request = new HttpRequestMessage() { RequestUri = new Uri(url), Method = HttpMethod.Get, }; for (int i = 0; i < formData.Count; i++) { request.Headers.Add(formData[i].Key, formData[i].Value); } var res = httpClient.SendAsync(request); res.Wait(); var resp = res.Result; Task temp = resp.Content.ReadAsStringAsync(); temp.Wait(); return temp.Result; }
關(guān)于C# .net core實(shí)現(xiàn)的網(wǎng)絡(luò)請(qǐng)求的方法就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的參考價(jià)值,可以學(xué)以致用。如果喜歡本篇文章,不妨把它分享出去讓更多的人看到。