webapi下的web请求

先看webapi提供的服务:

 1        [HttpPost]
 2         public ResultBaseModel SiteList(SiteModel param)
 3         {
 4             ResultBaseModel resultModel = new ResultBaseModel();
 5 
 6             var sites = new List<Site>();
 7 
 8 
 9             sites.Add(new Site { SiteId = 1, Title = "百度", Uri = "www.baidu.com" });
10             sites.Add(new Site { SiteId = 2, Title = "博客园首页", Uri = "www.cnblogs.com" });
11             sites.Add(new Site { SiteId = 3, Title = "博问", Uri = "q.cnblogs.com" });
12             sites.Add(new Site { SiteId = 4, Title = "新闻", Uri = "news.cnblogs.com" });
13             sites.Add(new Site { SiteId = 5, Title = "招聘", Uri = "job.cnblogs.com" });
14 
15             try
16             {
17 
18                 var result = (from Site site in sites
19                               where site.SiteId > param.StartId
20                               select site)
21                                 .Take(param.ItemCount)
22                                 .ToList();
23                 resultModel.IsSuccess = true;
24                 resultModel.Data = sites;
25 
26 
27             }
28             catch (Exception ex)
29             {
30                 resultModel.IsSuccess = false;
31                 resultModel.Message = ex.Message;
32             }
33 
34             return resultModel;
35         }

客户端调用:

1    var requestJson = JsonConvert.SerializeObject(new { StartId = 1, ItemCount = 3 });
2 
3             var url = "http://localhost:8084/api/CenterShedule/SiteList";
4             var responseJson = GetResponseWithNoContentPress(requestJson, url);
5             Console.WriteLine(responseJson);

通用的post方法:

 1         public static string GetResponseWithNoContentPress(string objStr, string url)
 2         {
 3             string result = "";
 4             StreamReader reader = null;
 5             System.IO.Stream stream = null;
 6             WebResponse response = null;
 7             HttpWebRequest request = null;
 8 
 9             try
10             {
11                 byte[] byteArray = Encoding.UTF8.GetBytes(objStr);
12                 request = (HttpWebRequest)WebRequest.Create(url);
13                 request.ContentType = "application/json; charset=urf-8";
14                 request.Accept = "application/json";
15                 request.ContentLength = byteArray.Length;
16                 request.KeepAlive = false;
17                 request.Method = "POST";
18                 request.Timeout = 600000;
19                 System.IO.Stream dataStream = request.GetRequestStream();
20                 dataStream.Write(byteArray, 0, byteArray.Length);
21                 dataStream.Close();
22                 response = request.GetResponse();
23                 stream = response.GetResponseStream();
24                 reader = new System.IO.StreamReader(stream, Encoding.UTF8);
25 
26                 result = reader.ReadToEnd();
27             }
28             catch (Exception ex)
29             {
30                 Console.WriteLine(ex.Message);
31             }
32             finally
33             {
34                 if (reader != null)
35                 {
36                     reader.Close();
37                 }
38                 if (stream != null)
39                 {
40                     stream.Close();
41                 }
42                 if (response != null)
43                 {
44                     response.Close();
45                 }
46                 if (request != null)
47                 {
48                     request.Abort();
49                     request = null;
50                 }
51             }
52             return result;
53         }
request.Accept = "application/json"; 这一句可以不用指定返回的类型,webapi自动返回json数据,可是我要返回xml数据怎么办?直接改:request.Accept = "application/xml";这时候请求会报错,报出服务器500错误。于是我改接口:

1        [HttpPost]
2         public string SiteList(SiteModel param)
3         {
4             return "hello world";
5         }

此时返回来的结果如下:

此时,我就想为什么之前的接口,返回不了数据呢?想了下应该是返回的model无法序列化成xml格式,如何让系统帮助生成xml,使用了各种办法,还是返回服务器500错误,最后决定还是自己写个序列化的方法。在此先不提。

post请求还有一种简洁的写法:

1           var requestJson = JsonConvert.SerializeObject(new { StartId = 1, ItemCount = 3 });
2 
3             HttpContent httpContent = new StringContent(requestJson);
4             httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
5 
6             var httpClient = new HttpClient();
7 
8             var responseJson = httpClient.PostAsync("http://localhost:8084/api/CenterShedule/SiteList", httpContent)
9                 .Result.Content.ReadAsStringAsync().Result;

 顺便把get请求的总结下:

 1  /// <summary>
 2         /// get请求,可以对请求头进行多项设置
 3         /// </summary>
 4         /// <param name="paramArray"></param>
 5         /// <param name="url"></param>
 6         /// <returns></returns>
 7         public static string GetResponseByGetFull(Dictionary<string, string> paramArray, string url)
 8         {
 9             string responseJson = "";
10 
11             var httpclient = HTTPHelper.HttpClient;
12 
13             url += BuildParam(paramArray);
14             var response = httpclient.GetAsync(url).Result;
15             if (response.IsSuccessStatusCode)
16             {
17                 Stream myResponseStream = response.Content.ReadAsStreamAsync().Result;
18                 StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
19                 responseJson = myStreamReader.ReadToEnd();
20                 myStreamReader.Close();
21                 myResponseStream.Close();
22             }
23 
24             return responseJson;
25         }

HttpClient:

 1    public class HTTPHelper
 2     {
 3         private static readonly HttpClient HttpClient;
 4         static HTTPHelper()
 5         {
 6             var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.None };
 7             HttpClient = new HttpClient(handler);
 8 
 9             HttpClient.DefaultRequestHeaders.Accept.Clear();
10             HttpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
11         }
BuildParam:
 1        private static string BuildParam(Dictionary<string, string> paramArray)
 2         {
 3             string url = "";
 4             if (paramArray != null && paramArray.Count > 0)
 5             {
 6                 var parms = "";
 7                 foreach (var item in paramArray)
 8                 {
 9                     parms += string.Format("{0}={1}&", item.Key, item.Value);
10                 }
11                 if (parms != "")
12                 {
13                     parms = "?" + parms.TrimEnd('&');
14                 }
15                 url += parms;
16 
17             }
18             return url;
19         }

 

 
posted @ 2017-07-10 15:58  micDavid  阅读(225)  评论(0编辑  收藏  举报