2.然后创建一个通用方法的类库:Common
3.在类库中添加接口发送与请求的通用方法:HttpHelper.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| public class HttpHelper { /// <summary> /// 调用api返回json /// </summary> /// <param name="url">api地址</param> /// <param name="jsonstr">接收参数</param> /// <param name="type">类型</param> /// <returns></returns> public static string HttpApi(string url, string jsonstr, string type) { Encoding encoding = Encoding.UTF8; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//webrequest请求api地址 request.Accept = "*/*"; request.ContentType = "application/json"; request.Method = type.ToUpper().ToString();//get或者post byte[] buffer = encoding.GetBytes(jsonstr); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { return reader.ReadToEnd(); } } }
|
4.添加JSON序列化与反序列化的引用
由于我们接口的传参和相应结果用的JSON格式,因此要用到:Newtonsoft.Json,用于实现数据的JSON序列化和反序列化;
添加引用的方法:
在项目中右键”引用“,点选”管理NuGet程序包“》浏览》搜索:Newtonsoft.Json》点击安装即可;
5.接口的调用
1 2 3 4 5 6 7 8
| var url = " 你的接口名"; //参数 var data = new { id = 10 };
var result =(JObject)JsonConvert.DeserializeObject(HttpHelper.HttpApi(url, JsonConvert.SerializeObject(data), "post"));
|
这里我的reslut包含了:msg,code,data 三个对象,取值的方式为:
result[“msg”]
result[“code”]
result[“data”]