代码改变世界

使用HttpClient 调用Web Api

2016-06-16 14:02  taozsay  阅读(346)  评论(0编辑  收藏  举报

C#4.5 添加了异步调用Web Api 。

如果你的项目是4.5以上版本,可以直接参考官方文档。

http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client

 

现在项目使用的是C# 4.0 ,需要对HttpClient 进行修改。

当然了你要先添加两个引用 Microsoft.Net.Http和Microsoft.AspNet.WebApi.Client

下面是改造后的HttpClient 

public class ResultMessage
     {
         public string Code { get; set; }
         public string Message { get; set; }
         public string Content { get; set; }
     }
 
     public class HttpClientHelper
     {
         public static string RequestUrl = "http://localhost:1282/";
 
         /// <summary>
         ///     HttpClient实现Get请求
         /// </summary>
         public static ResultMessage Get(string url)
         {
             using (var client = new HttpClient())
             {
                 client.BaseAddress = new Uri(RequestUrl);
                 client.DefaultRequestHeaders.Accept.Clear();
                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 
                 Task<HttpResponseMessage> response = client.GetAsync(url);
                 var resultMsg = new ResultMessage();
                 if (response.Result.IsSuccessStatusCode)
                 {
                     Task<string> content = response.Result.Content.ReadAsStringAsync();
                     string resultjson = content.Result;
                     resultMsg = JsonConvert.DeserializeObject<ResultMessage>(resultjson);
                     Console.WriteLine("{0}\t{1}\t{2}", resultMsg.Code, resultMsg.Message, resultMsg.Content);
                 }
                 else
                 {
                     resultMsg.Code = response.Result.StatusCode.ToString();
                     resultMsg.Message = response.Result.ReasonPhrase;
                     Console.WriteLine("{0} ({1})", (int) response.Result.StatusCode, response.Result.ReasonPhrase);
                 }
 
                 return resultMsg;
             }
         }
 
         /// <summary>
         ///     HttpClient实现Post请求
         ///     执行服务方法
         /// </summary>
         public static ResultMessage Post(string code, string name)
         {
             string url = RequestUrl + "api/Biz/Exec";
 
             using (var client = new HttpClient())
             {
                 client.BaseAddress = new Uri(RequestUrl);
                 client.DefaultRequestHeaders.Accept.Clear();
                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 
                 var content = new FormUrlEncodedContent(new Dictionary<string, string>
                 {
                     {"code",code}
                     {"name",name},
                 });
                 var resultMsg = new ResultMessage();
                 Task<HttpResponseMessage> response = client.PostAsync(url, content);
                 //延时处理
                 if (response.Result.IsSuccessStatusCode)
                 {
                     Task<string> con = response.Result.Content.ReadAsStringAsync();
                     string resultjson = con.Result;
                     resultMsg = JsonConvert.DeserializeObject<ResultMessage>(resultjson);
                 }
                 else
                 {
                     resultMsg.Code = response.Result.StatusCode.ToString();
                     resultMsg.Message = response.Result.ReasonPhrase;
                 }
 
                 return resultMsg;
             }
         }
     }