Objective
This tutorial demonstrates a console application that uses HttpClient to invoke the Web API. We will also use the Web API established in the previous tutorial. You can get the Web API built directly by finding the appropriate download link in the http://www.cnblogs.com/aehyok/p/3434578.html article.
We also created the test project through VS2013. This tutorial sample code download link Http://pan.baidu.com/s/1mrObX
Setting up a console project
Start by creating a simple console application and then using NuGet to get Microsoft.AspNet.WebApi.Client.
You can install the Web API client library by searching and then clicking Install.
Add model to your project
Using System; Using System.Collections.Generic; Using System.Linq; Using System.Text; Using System.Threading.Tasks; Namespace callwebapi{public class Product {public string Name {get; set} public double price {get; set;} public String Category {get; set;}} }
This class creates a data object that httpclient can write to in the HTTP request body, or it can be read from the HTTP response body.
Initialize HttpClient
Create a new HttpClient example, as follows:
Using System; Using System.Collections.Generic; Using System.Linq; Using System.Net.Http; Using System.Net.Http.Headers; Using System.Text; Using System.Threading.Tasks; Namespace Callwebapi{class program {static void Main (string[] args) { HttpClient client = new HttpClient (); client. baseaddress = new Uri ("http://localhost:4115/"); Client. DEFAULTREQUESTHEADERS.ACCEPT.ADD (New Mediatypewithqualityheadervalue ("Application/json"));}}}
This is the application execution effect show in the previous tutorial
So the code above US
Client. baseaddress = new Uri ("http://localhost:4115/");
It then adds a JSON-formatted accept header. It tells the server to accept headers to send data in JSON format.
Get resources through the HTTP GET method
The following code is how to use the API to query the product Information list.
Httpresponsemessage response = client. Getasync ("Api/products"). Result; if (response. Issuccessstatuscode) {var products = response. Content.readasasync<ienumerable<product>> (). Result; foreach (var p in products) { Console.WriteLine ("{0}\t{1};\t{2}", P.name, P.price, p.category); } } else { Console.WriteLine ("{0} ({1})", (int) response. StatusCode, Response. reasonphrase); }
This Getasync method sends an HTTP GET request. As the name implies, this Getasync method is asynchronous. It returns immediately without waiting for a response from the server. This return value represents a task object for an asynchronous operation. When this operation is complete, this Task.result property contains the HTTP response.
If the HTTP response indicates success, the response body will contain a list of product information in a JSON format. In order to parse this list, you need to call Readasasync. This method reads the response body and attempts to serialize to a specified CLR type. This method is also asynchronous, because the body of the response can be arbitrarily large.
Request headers for Api/products
Response Headers for api/products
Response Body for Api/products
The final call results are shown in the console as follows
Get a product information with a product ID
Get a product information with a Product ID response = client. Getasync ("API/PRODUCTS/1"). Result; if (response. Issuccessstatuscode) {var product = response. Content.readasasync<product> (). Result; Console.WriteLine ("{0}\t{1};\t{2}", product. Name, product. Price, product. Category); } else { Console.WriteLine ("{0} ({1})", (int) response. StatusCode, Response. reasonphrase); }
Media Type format identity
Readasasync is an extension method defined in the System.Net.Http.HttpContentExtensions class. Without parameters, it uses the default media type format to identify the setting and tries to parse the response body. This default format identifier supports JSON, XML, and form-url-encoded data.
You can explicitly specify the media type format identifier to use. This is very useful if you have a custom media type format identity.
var formatters = new List<mediatypeformatter> () {new Mycustomformatter (), New Jsonmediatypeformatter (), New XmlMed Iatypeformatter ()};resp. Content.readasasync<ienumerable<product>> (formatters);
Add a resource via HTTP POST
The following code sends a POST request that contains a JSON-formatted product entity.
HTTP POST request var gizmo = new Product () {Name = "gizmo", Price = +, Category = "Widget"}; Uri Gizmouri = null; Response = client. Postasjsonasync ("Api/products", Gizmo). Result; if (response. Issuccessstatuscode) { Gizmouri = response. headers.location; } else { Console.WriteLine ("{0} ({1})", (int) response. StatusCode, Response. reasonphrase); }
Postasjsonasync is an extension method defined in the System.Net.Http.HttpContentExtensions class. It is equivalent to the following:
var product = new Product () {Name = "Gizmo", Price = +, Category = "Widget"}; Mediatypeformatter jsonformatter = new Jsonmediatypeformatter (); Httpcontent content = new Objectcontent<product> (Product, Jsonformatter); var resp = client. Postasync ("api/products", content). Result;
For the type of XML format, use this Postasxmlasync method.
By default, this JSON format indicates that the setting Content-type is "Application/json". You can also specify a media type explicitly. For example, "Application/vnd.example.product" is the media type of your product entity. You can set the media type as follows:
Httpcontent content = new Objectcontent<product> (Product, Jsonformatter, "Application/vnd.example.product+json ");
Modify a resource with an HTTP put
The following code sends a PUT request (then the entity added above is modified)
Gizmo. Price = 99.9; Response = client. Putasjsonasync (Gizmouri.pathandquery, Gizmo). Result; Console.WriteLine ("{0} ({1})", (int) response. StatusCode, Response. Reasonphrase);
This Putasjsonasync method works like Postasjsonasync , except that it sends a PUT request instead of post.
Delete a resource via HTTP delete
By now, you can predict how to send a delete request.
Delete a resource response = client. Deleteasync (Gizmouri). Result; Console.WriteLine ("{0} ({1})", (int) response. StatusCode, Response. Reasonphrase);
Like get, a delete request does not have a request body, so you do not need to specify a JSON or XML format.
Error handling
HttpClient does not throw an exception when it receives an HTTP response to an error code. Instead, this status code is included in the status code attribute of this response. Additionally, if the status is a success code (a status code in the 200-299 range), theIssuccessstatuscode property is true.
In the example above we have used this pattern:
Httpresponsemessage response = client. Getasync ("Api/products"). Result; if (response. Issuccessstatuscode) {//...}
If you prefer to see the error code as an exception, call this Ensuresuccessstatuscode method. If the response state is not a successful status code, then this method throws an exception.
try {var resp = client. Getasync ("Api/products"). Result; Resp. Ensuresuccessstatuscode (); Throw if not a success code. // ... } catch (Httprequestexception e) { Console.WriteLine (e.message);}
Configure HttpClient
If you want to configure HttpClient, create an Webrequesthandler instance, set its properties, and pass it to the HttpClient constructor:
Webrequesthandler handler = new Webrequesthandler () { AllowAutoRedirect = False, UseProxy = false}; HttpClient client = new HttpClient (handler);
Webrequesthandler derived from httpmessagehandler . You can also insert a custom message handler by deriving from Httpmessagehandler . For more information, see HTTP message handlers (temporarily not implemented)
Summarize
This article source link http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client
One step at a learning, still very rewarding. Some of these areas do not understand and need to be digested slowly.
ASP. 2 Third Lesson ——. NET client invoke Web API