C# 调用webApi接口的方法(类库HttpClient)
一、类库HttpClient,用于发送http请求
类似于axios,ajax等,无第三方依赖。
注意,这里的请求类型为application/json,你可以根据自己的需求的不同进行封装
using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Net; namespace UnifyPayPlatAPI.Controller { public class HttpClient { /// <summary> /// 接口地址 /// </summary> public string Url { get; set; } /// <summary> /// 内容,body,fields参数 /// </summary> public string Data { get; set; } /// <summary> /// Cookie,保证登录后,所有访问持有一个Cookie; /// </summary> static CookieContainer Cookie = new CookieContainer(); /// <summary> /// Seivice Method ,post,get,delete,put,等等,支持大小写 /// </summary> public string Method { get; set; } /// <summary> /// 请求头 /// </summary> public Dictionary<string, string> Headers { get; set; } /// <summary> /// 请求体类型 ,如application/json /// </summary> public string ContentType { get; set; } /// <summary> /// HTTP访问 /// </summary> public string AsyncRequest() { HttpWebRequest httpRequest = HttpWebRequest.Create(Url) as HttpWebRequest; httpRequest.Method = Method; if (Headers != null && Headers.Count > 0) { for (int i = 0; i < Headers.Keys.Count; i++) { string key = Headers.Keys.ElementAt(i); httpRequest.Headers.Add(key, Headers[key]); } } httpRequest.ContentType = string.IsNullOrEmpty(ContentType) ? "application/json" : ContentType; httpRequest.CookieContainer = Cookie; httpRequest.Timeout = 1000 * 60 * 10;//10min using (Stream reqStream = httpRequest.GetRequestStream()) { var bytes = UnicodeEncoding.UTF8.GetBytes(Data); reqStream.Write(bytes, 0, bytes.Length); reqStream.Flush(); } using (var repStream = httpRequest.GetResponse().GetResponseStream()) { using (var reader = new StreamReader(repStream)) { return ValidateResult(reader.ReadToEnd()); } } } private static string ValidateResult(string responseText) { if (responseText.StartsWith("response_error:")) { return responseText.TrimStart("response_error:".ToCharArray()); } return responseText; } } }
二、Json依赖
依赖于Newtonsoft.Json,需要去NuGet安装;
三、请求方式
3.1 方式一
//创建访问webapi必备对象 HttpClient httpClient = new HttpClient(); httpClient.Url = apiUrl611; httpClient.Data = JsonInput; httpClient.Method = "Post"; var JsonOut = httpClient.AsyncRequest(); var iResult = JObject.Parse(httpClient.AsyncRequest());
3.2 方式二
string data = "{ "username": "zhangsan","password": "123456"}"; Dictionary<string, string> headers = new Dictionary<string, string>(); headers.Add("zhangsan","testToken123456"); //向后端发送请求 HttpClient httpClient = new HttpClient(); httpClient.Url = "http://localhost:5555/login"; httpClient.Method = "post"; httpClient.Data = data; httpClient.Headers = headers; //httpClient.ContentType = "application/json"; //不设置默认为application/json //返回结果 //处理方式一 var iResult = JObject.Parse(httpClient.AsyncRequest()); int code = iResult ["code"].Value<int>(); string message = iResult ["message"].Value<string>; JArray roles = iResult ["roles"] as JArray; JArray roles = JArray.Parse(iResult ["roles"]); //处理方式二 string iResult = httpClient.AsyncRequest(); //反序列化,当然你要先定义一个数据模型,负责接收反序列化后的数据 //为数据模型的类型 T res = JsonConvert.DeserializeObject<T>(iResult);
拓展: