.NET WEB后端POST和GET请求

来源:互联网 发布:阿里云cdn缓存配置 编辑:程序博客网 时间:2024/06/04 19:27

最近学习了一下,关于.NET后端对其他网页提供的公共接口访问,目前是对数据没有加密和解密的考虑,后期会增加MD5加密和对称加密的封装方法;
POST和GET请求对于对接接口使用很常见;闲话不多说,先来一段代码:如果使用的MVC框架需要提供一个WEBAPI的接口;
第一步:提供接口;我们在这里提供了一个简单的控制器接口实现:

 //继承ApiController的方法 public class DemoController : ApiController    {        //带参数的实现方法        public IList<Site> SiteList(int startId, int itemcount)        {            var sites = new List<Site>();//数据源           //(可以根据后台动态获取,扩展成为访问数据库的方法),这里  我就直接赋值采用最简单的方式            sites.Add(new Site { SiteId = 1, Title =       "test", Uri = "blog.csdn.net" });            sites.Add(new Site { SiteId = 2, Title = "百度首页", Uri = "www.baidu.com" });            sites.Add(new Site { SiteId = 3, Title = "必应", Uri = "cn.bing.com" });            var result = (from Site site in sites                          where site.SiteId > startId                          select site)                            .Take(itemcount)                            .ToList();            return result;        }    }

然后,需要我们写一个单元测试访问一下我们的接口是否有问题,返回的数据是否正确,测试用例:

  public void TestMethod()        {            //构建传入的参数            var requestJson = JsonConvert.SerializeObject(new { startId = 1, itemcount = 3 });            //封装成为一个对象            HttpContent httpContent = new StringContent(requestJson);            //增加一个请求头部            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");            var httpClient = new HttpClient();            //采取POST请求            var responseJson = httpClient.PostAsync("http://localhost:9000/api/demo/sitelist", httpContent).Result.Content.ReadAsStringAsync().Result;            //将请求的数据进行序列化            var sites = JsonConvert.DeserializeObject<IList<Site>>(responseJson);            //遍历解析数据            sites.ToList().ForEach(x => Console.WriteLine(x.Title + ":" + x.Uri));        }   

测试通过之后该接口就可以提供给其他第三方或者自己使用了(注:这是一个流程,目前我们这个只是用来练习的)
下面我将POST和GET请求做了方法封装 :
1、GET类型的Web请求

        /// <summary>        /// 发起一个GET类型的Web请求,并返回响应        /// </summary>        /// <param name="requestUri">请求地址</param>        /// <returns>响应</returns>        public static string SendGetRequest(string requestUri)        {            if (requestUri.IfNull().ToLower().Trim().StartsWith("https"))            {                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;            }            //创建GET请求            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);            httpWebRequest.Method = "GET";            HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();            Stream responseStream = response.GetResponseStream();            StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);            string content = reader.ReadToEnd();            //注意请求完成需要关闭流和上下文            reader.Close();            responseStream.Close();            response.Close();            return content;        }  

2、POST类型的Web请求

        /// <summary>        /// 发起一个POST类型的Web请求,并返回响应        /// </summary>        /// <param name="requestUri">请求地址</param>        /// <param name="jsonData">json数据包</param>        /// <returns>响应</returns>        public static string SendPostRequest(string requestUri, string jsonData)        {            if (requestUri.IfNull().ToLower().Trim().StartsWith("https"))            {                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;            }            //创建POST请求            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);            byte[] data = Encoding.UTF8.GetBytes(jsonData);            httpWebRequest.Method = "POST";            httpWebRequest.ContentType = "application/x-www-form-urlencoded";            httpWebRequest.ContentLength = data.Length;            httpWebRequest.KeepAlive = true;            using (var requestStream = httpWebRequest.GetRequestStream())            {                requestStream.Write(data, 0, data.Length);            }            HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();            Stream responseStream = response.GetResponseStream();            StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);            //注意请求完成需要关闭流和上下文            string content = reader.ReadToEnd();            reader.Close();            responseStream.Close();            response.Close();            return content;        }
1 0
原创粉丝点击