使用RestSharp 库消费Restful
Service
中介绍了一个开源的Http Client库RestSharp。在ASP.NET MVC
4中也带来.NET框架中的Http
Client.aspx)。它提供了一个心灵手巧的、可扩大的API来访问一切经过HTTP公开之RESTful服务。HttpClient是ASP.NET
Web API 的同样局部,直接包含在.NET
4.5遭,也可以独自安装ASP.NET
MVC4,可以经Nuget包拿走,包中含以下3有些:

  • System.Net.Http: The main NuGet package providing the basic
    HttpClient and related classes
  • System.Net.Http.Formatting: Adds support for serialization,
    deserialization as well as for many additional features building on
    top of System.Net.Http
  • System.Json: Adds support for JsonVaue which is a mechanism for
    reading and manipulating JSON documents

HttpClient是收纳HttpResponseMessages和殡葬HttpRequestMessages的主要类,如果您习以为常了应用WebClient或者是HttpWebRequest,
需要专注HttpClient和他们不同的地方:

1、在HttpClient实例上配备扩展,设置默认的首,取消不成功的求与重新多之设置。

2、你通过一个单纯的HttpClient实例,它发出友好之连接池。

3、HttpClients不跟一定的HTTP服务器绑定,你可行使同一之HttpClient实例提交任何HTTP请求。

4、你可用HttpClient为特定的站点创建特殊的Client

5、HttpClient采用新的品种模式处理异步请求而她又爱管理及和谐更多之请。

下面我们看下实际的代码,MSDN code
gallery
有个老详细Get操作的示范,这个示例是为World Bank Data Web
API 发送一个Get请求,获取到Json格式的数量

namespace WorldBankSample 

    /// <summary> 
    /// Sample download list of countries from the World Bank Data
sources at http://data.worldbank.org/ 
    /// </summary> 
    class Program 
    { 
        static string _address =
“http://api.worldbank.org/countries?format=json”; 
 
        static void Main(string[] args) 
        { 
            // Create an HttpClient instance 
            HttpClient client = new HttpClient(); 
 
            // Send a request asynchronously continue when complete 
            client.GetAsync(_address).ContinueWith( 
                (requestTask) => 
                { 
                    // Get HTTP response from completed task. 
                    HttpResponseMessage response =
requestTask.Result; 
 
                    // Check that response was successful or throw
exception 
                    response.EnsureSuccessStatusCode(); 
 
                    // Read response asynchronously as JsonValue and
write out top facts for each country 
                   
response.Content.ReadAsAsync<JsonArray>().ContinueWith( 
                        (readTask) => 
                        { 
                            Console.WriteLine(“First 50 countries listed
by The World Bank…”); 
                            foreach (var country in
readTask.Result[1]) 
                            { 
                                Console.WriteLine(”   {0}, Country Code:
{1}, Capital: {2}, Latitude: {3}, Longitude: {4}”, 
                                    country.Value[“name”], 
                                    country.Value[“iso2Code”], 
                                    country.Value[“capitalCity”], 
                                    country.Value[“latitude”], 
                                    country.Value[“longitude”]); 
                            } 
                        }); 
                }); 
 
            Console.WriteLine(“Hit ENTER to exit…”); 
            Console.ReadLine(); 
        } 
    } 

下面介绍一个殡葬Post 请求的演示,示例代码用默认创建的ASP.NET Web
API模板项目:

public class ValuesController : ApiController
   {
       // GET /api/values
       public IEnumerable<string> Get()
       {
           return new string[] { “value1”, “value2” };
       }

       // GET /api/values/5
       public string Get(int id)
       {
           return “value”;
       }

       // POST /api/values
       public string Post(string value)
       {
           return value;
       }

       // PUT /api/values/5
       public void Put(int id, string value)
       {
       }

       // DELETE /api/values/5
       public void Delete(int id)
       {
       }
   }

以HttpClient示例的代码如下:

          string serviceAddress =
“http://localhost:2650/api/values”;
           HttpWebRequest request =
(HttpWebRequest)HttpWebRequest.Create(serviceAddress);
           request.Method = “POST”;
           request.ContentType = “application/json”;
           string strContent = @”{ “”value””: “”test””}” ;
           using (StreamWriter dataStream = new
StreamWriter(request.GetRequestStream()))
           {
               dataStream.Write(strContent);
               dataStream.Close();
           }
           HttpWebResponse response =
(HttpWebResponse)request.GetResponse();
           using (StreamReader dataStream = new
StreamReader(response.GetResponseStream()))
           {
               var result = dataStream.ReadToEnd();
               Console.WriteLine(result);
           }

            Uri serviceReq = new Uri(serviceAddress);
            HttpClient client = new HttpClient();
            HttpContent content = new StringContent(@”{ “”value””:
“”test””}”);
            content.Headers.ContentType = new
MediaTypeHeaderValue(“application/json”);

            // Send a request asynchronously continue when complete
            client.PostAsync(serviceReq, content).ContinueWith(
                (requestTask) =>
                {
                    // Get HTTP response from completed task.
                    HttpResponseMessage response = requestTask.Result;

                    // Check that response was successful or throw
exception
                    response.EnsureSuccessStatusCode();

                    // Read response asynchronously as JsonValue and
write out top facts for each country
                   
response.Content.ReadAsAsync<string>().ContinueWith(
                        (readTask) =>
                        {
                            Console.WriteLine(readTask.Result);

                        });
                });

方代码首先是创办一个HttpClient实例,设置要Post的数码的格式,然后调用HttpClient的异步请求,获取到的凡一个HttpResponseMessage实例,可以以斯实例中检查请求的状态,调用的是一个扩展方法EnsureSuccessStatusCode,如果无是HttpStatusCode.OK,就会扔来一个好。通过HttpResponseMessage的Content属性获取HttpContent,HttpContent有一些方式帮助处理接收的内容。

对应于使用HttpWebRequest的言传身教如下:

          string serviceAddress =
“http://localhost:2650/api/values”;
           HttpWebRequest request =
(HttpWebRequest)HttpWebRequest.Create(serviceAddress);
           request.Method = “POST”;
           request.ContentType = “application/json”;
           string strContent = @”{ “”value””: “”test””}” ;
           using (StreamWriter dataStream = new
StreamWriter(request.GetRequestStream()))
           {
               dataStream.Write(strContent);
               dataStream.Close();
           }
           HttpWebResponse response =
(HttpWebResponse)request.GetResponse();
           using (StreamReader dataStream = new
StreamReader(response.GetResponseStream()))
           {
               var result = dataStream.ReadToEnd();
               Console.WriteLine(result);
           }

地方是经过代码发送的Http请求,也可以为此Fiddlers来验证请求,例如:

图片 1

图片 2

相关文章

网站地图xml地图