調用主體
Get請求

var httpClient = new HttpClient(); var getTokenUrl = new Uri("接口網絡地址"); var response = httpClient.GetAsync(getTokenUrl).Result; var data = response.Content.ReadAsStringAsync().Result;//接口調用成功獲取的數據 JObject jsonInfo = (JObject)JsonConvert.DeserializeObject(data); string code = Convert.ToString(jsonInfo["errcode"]);
Post請求
此處例舉的是傳headers,如果不需要注釋掉

#region 調用接口(postman) string Url = "http://?.?.?.?:9900/weather";//請求的url地址 //string ContentTypeS = "application/x-www-form-urlencoded"; //格式類型(x-www-form-urlencoded格式傳參) string ContentTypeS = "application/json"; //格式類型(json格式傳參) //string PostData = "mode=" + "insert" + "&data=" + json; //傳送的數據(x-www-form-urlencoded傳參) sendCS sendcs = new sendCS(); sendcs.mode = "insert"; sendcs.data = "12345"; string jkid = "12345"; //轉json string PostData = JsonConvert.SerializeObject(sendcs); //傳送的數據(json傳參) RestApiClient DXApiManager = new RestApiClient(Url, HttpVerbNew.POST, ContentTypeS, PostData, jkid); string returnInfo = DXApiManager.MakeRequest(); //轉為json對象(添加Newtonsoft.Json.dll引用) JObject jsonInfo = (JObject)JsonConvert.DeserializeObject(returnInfo); string code = Convert.ToString(jsonInfo["code"]);//輸出 結果 string msg = Convert.ToString(jsonInfo["msg"]);//輸出 結果 //再根據code返回值去判斷成功或失敗,返回結果 #endregion
相關類

public class RestApiClient { public string EndPoint { get; set; } //請求的url地址 public HttpVerbNew Method { get; set; } //請求的方法 public string ContentType { get; set; } //格式類型 public string PostData { get; set; } //傳送的數據 public string JKID { get; set; } //headers 參數 public RestApiClient() { EndPoint = ""; Method = HttpVerbNew.GET; ContentType = "text/xml"; PostData = ""; } public RestApiClient(string endpoint, string contentType) { EndPoint = endpoint; Method = HttpVerbNew.GET; ContentType = contentType; PostData = ""; } public RestApiClient(string endpoint, HttpVerbNew method, string contentType) { EndPoint = endpoint; Method = method; ContentType = contentType; PostData = ""; } public RestApiClient(string endpoint, HttpVerbNew method, string contentType, string postData,string jkid) { EndPoint = endpoint; Method = method; ContentType = contentType; PostData = postData; JKID = jkid; } // 添加https private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { if (errors == SslPolicyErrors.None) return true; return false; } // end添加https public string MakeRequest() { return MakeRequest(""); } public string MakeRequest(string parameters) { // 添加https if (EndPoint.Substring(0, 8) == "https://") { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; } var request = (HttpWebRequest)HttpWebRequest.Create(EndPoint + parameters); if (EndPoint.Substring(0, 8) == "https://") { //string clientp12path = AppDomain.CurrentDomain.BaseDirectory + "\\Certificate\\outgoing.CertwithKey.pkcs12"; //string clientp12PassWord = "IoM@1234"; //string clientp12path2 = AppDomain.CurrentDomain.BaseDirectory + "\\Certificate\\server.pem"; //string clientp12PassWord2 = "1qaz2wsx"; //X509Store certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine); //certStore.Open(OpenFlags.ReadOnly); //X509Certificate2 cer = new X509Certificate2(clientp12path, clientp12PassWord); //X509Certificate2 cer2 = new X509Certificate2(clientp12path2, clientp12PassWord2); //request.ClientCertificates.Add(cer); //request.ClientCertificates.Add(cer2); ServicePointManager.ServerCertificateValidationCallback += (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => { return true; }; request.UserAgent = DefaultUserAgent; } // end添加https request.Method = Method.ToString(); request.ContentLength = 0; request.ContentType = ContentType; request.ProtocolVersion = HttpVersion.Version10; request.Headers.Add("alpha_auth_token", "asdf12345"); request.Headers.Add("alpha_auth_jkid", JKID); if (!string.IsNullOrEmpty(PostData) && Method == HttpVerbNew.POST)//如果傳送的數據不為空,並且方法是post { var encoding = new UTF8Encoding(); var bytes = Encoding.UTF8.GetBytes(PostData);//編碼方式按自己需求進行更改,我在項目中使用的是UTF-8 request.ContentLength = bytes.Length; using (var writeStream = request.GetRequestStream()) { writeStream.Write(bytes, 0, bytes.Length); } } else if (!string.IsNullOrEmpty(PostData) && Method == HttpVerbNew.PUT)//如果傳送的數據不為空,並且方法是put { var encoding = new UTF8Encoding(); var bytes = Encoding.UTF8.GetBytes(PostData);//編碼方式按自己需求進行更改,我在項目中使用的是UTF-8 request.ContentLength = bytes.Length; using (var writeStream = request.GetRequestStream()) { writeStream.Write(bytes, 0, bytes.Length); } } using (var response = (HttpWebResponse)request.GetResponse()) { var responseValue = string.Empty; if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.NoContent && response.StatusCode != HttpStatusCode.Created) { var message = response.StatusCode.ToString(); throw new ApplicationException(message); } // grab the response using (var responseStream = response.GetResponseStream()) { if (responseStream != null) using (var reader = new StreamReader(responseStream)) { responseValue = reader.ReadToEnd(); } } return responseValue; } } } public enum HttpVerbNew { GET, //method 常用的就這幾樣,可以添加其他的 get:獲取 post:修改 put:寫入 delete:刪除 POST, PUT, DELETE }
httpclient萬能寫法
現在postman越來越便利,當我們用postman調通接口后,可直接一鍵成生code(postman版本不同位置不同)
舉例:
點擊后可一鍵生成代碼 扔進項目里就可運行 前提!!!需要添加一個NuGet包 --- RestSharp