您好,登錄后才能下訂單哦!
這篇文章給大家介紹怎么在c#中通過發(fā)送請(qǐng)求訪問外部接口,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
string url = "https://cloud.soei.com.cn/smsapi/sms/verifycode"; HttpClient httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(url); //表頭參數(shù) string token = "9c0025b4aae442bda5498971ec1ab219"; httpClient.DefaultRequestHeaders.Add("token", token); httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); try { using (var request = new HttpRequestMessage()) { var postBody = $"{{\"identity\":\"{identity}\",\"phoneNumber\":\"{phoneNumber}\",\"code\":\"[code]\"}}"; request.Method = HttpMethod.Post; request.Content = new StringContent(postBody, Encoding.UTF8, "application/json"); var response = await httpClient.SendAsync(request); //返回結(jié)果 var retString = await response.Content.ReadAsStringAsync(); JObject items = (JObject)JsonConvert.DeserializeObject(retString); //返回碼,成功為200 string retCode = items["code"].ToString(); 返回消息 string message = items["message"].ToString(); string data = items["data"].ToString(); JObject items_data = (JObject)JsonConvert.DeserializeObject(data); string isSuccess = items_data["isSuccess"].ToString(); string data_message = items_data["message"].ToString(); if (isSuccess == "False") { retCode = "300"; } retMessage.retCode = retCode; retMessage.message = data_message; } } catch (Exception e) { retMessage.retCode = "300"; retMessage.message = e.Message.ToString(); } return retMessage; }
public static async Task<string> PostData(string path,string serverPath,dynamic param) { try { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Referer", string.Format("http://{0}", serverPath)); HttpResponseMessage response; using (HttpContent httpContent = new StringContent(param, Encoding.UTF8)) { httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); //client.DefaultRequestHeaders.Add("x-token", "M3Q_mQEwmn9l4Ly7fM7DxaMSdlYSSup5lfKLztF_VP97Urf"); response = await client.PostAsync(path, httpContent).ContinueWith(res => { return res; }).Result; } if (response != null && response.IsSuccessStatusCode) { return await response.Content.ReadAsStringAsync(); } else { return string.Empty; } } catch (Exception ex) { throw; } finally { } }
補(bǔ)充:C#后臺(tái)調(diào)用Http外網(wǎng)接口(GET, POST)
1.get方法調(diào)用接口獲取json文件內(nèi)容
public void GetFunction() { string serviceAddress = "http://222.111.999.444:8687/tttr/usercrd/12/b7e50cb45a?userid=9999"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); Response.Write(retString); }
這個(gè)太復(fù)雜了 突然發(fā)現(xiàn)個(gè)簡(jiǎn)單的:
using (var client = new WebClient()){ client.Encoding = Encoding.UTF8; string serviceAddress = urlappend + "cloud/device/data/getErrorData?appId=" + appid + "&accessToken=" + accessToken + "×tamp=" + time + "&deviceIds=" + deviceIds; var data = client.DownloadString(serviceAddress); var obj = JsonConvert.DeserializeObject<JObject>(data); } //obj就是返回?cái)?shù)據(jù)的對(duì)象
2.post方法調(diào)用接口獲取json文件內(nèi)容
public void PostFunction() { string serviceAddress = "http://222.111.999.444:8687/tttr/usercrd/uuu/12/dfd7e4"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress); request.Method = "POST"; request.ContentType = "application/json"; string strContent = @"{ ""mmmm"": ""89e"",""nnnnnn"": ""0101943"",""kkkkkkk"": ""e8sodijf9""}"; using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream())) { dataStream.Write(strContent); dataStream.Close(); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string encoding = response.ContentEncoding; if (encoding == null || encoding.Length < 1) { encoding = "UTF-8"; //默認(rèn)編碼 } StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)); string retString = reader.ReadToEnd(); //解析josn JObject jo = JObject.Parse(retString); Response.Write(jo["message"]["mmmm"].ToString()); }
關(guān)于怎么在c#中通過發(fā)送請(qǐng)求訪問外部接口就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。