RESTSHARP Instructions for use

Source: Internet
Author: User
Tags dateformat http authentication

Translated from: Github.com/restsharp/restsharp/wiki, please specify.

First, the introduction of beginners

If only a few one-time requests need to be encapsulated as APIs, you can use Restsharp as follows:

using RestSharp;using RestSharp.Authenticators;var client = new RestClient();client.BaseUrl = new Uri("http://twitter.com");client.Authenticator = new HttpBasicAuthenticator("username", "password");var request = new RestRequest();request.Resource = "statuses/friends_timeline.xml";IRestResponse response = client.Execute(request);

The Irestresponse interface contains information returned by all remote services and can access header information (content), HTTP status, and so on. It is recommended that you use generics to automatically deserialize the returned results. NET entity class.

About error Handling:

If a network transmission error occurs (network paralysis, DNS lookup failure, and so on), Restresponse.responsestatus will be set to error, otherwise the value of Restresponse.responsestatus is completed. If the API returns 404,responsestatus is still completed. If you need to access the returned HTTP status code, you need to see the value of the Restresponse.statuscode, which is the identity of the request completion, independent of the API error handling.

Second, recommended usage

Restsharp is suitable as the basis for implementing API proxy classes, here are some examples of use in the Twilio class library:

The

Creates a class that contains an API proxy implementation that declares an execution method as a portal to all requests. This execution method allows you to set common parameters and other cross-request sharing settings, such as authentication, because each request requires an account ID and key, so you need to pass both values when creating a new proxy instance. It is important to note that exceptions are not thrown during execution, but exception information can be accessed in errorexception.

Twilioapi.cspublic class Twilioapi {const string BASEURL = "api.twilio.com/2008-08-01";    ReadOnly string _accountsid;    ReadOnly string _secretkey;        Public Twilioapi (String accountsid, String secretkey) {_accountsid = Accountsid;    _secretkey = Secretkey;        Public T execute<t> (restrequest request) where T:new () {var client = new Restclient (); Client.        BASEURL = new System.Uri (BASEURL); Client.        Authenticator = new Httpbasicauthenticator (_accountsid, _secretkey); Request. Addparameter ("Accountsid", _accountsid, parametertype.urlsegment); Used on every request var response = client.        Execute<t> (Request); if (response.  Errorexception! = null) {const string message = "Error retrieving response.            Check inner details for more info. "; var twilioexception = new ApplicationException (message, Response.            Errorexception);        Throw twilioexception; } return ResponsE.data; }}

Next, define an entity class to map the data returned by the API, and then define a method to access the API to get the specific information returned by the call resource:

// Call.cspublic class Call{    public string Sid { get; set; }    public DateTime DateCreated { get; set; }    public DateTime DateUpdated { get; set; }    public string CallSegmentSid { get; set; }    public string AccountSid { get; set; }    public string Called { get; set; }    public string Caller { get; set; }    public string PhoneNumberSid { get; set; }    public int Status { get; set; }    public DateTime StartTime { get; set; }    public DateTime EndTime { get; set; }    public int Duration { get; set; }    public decimal Price { get; set; }    public int Flags { get; set; }}// TwilioApi.cs, method of TwilioApi classpublic Call GetCall(string callSid) {    var request = new RestRequest();    request.Resource = "Accounts/{AccountSid}/Calls/{CallSid}";    request.RootElement = "Call";    request.AddParameter("CallSid", callSid, ParameterType.UrlSegment);    return Execute<Call>(request);}

Some of the magic is that restsharp need to care and we don't have to focus on:

1. The XML data returned by the API is detected by default Xmldeserializer and deserialized as a call object.

2, the default restrequest corresponds to the GET request in HTTP, you can change the request type by setting the method property of the Restrequest or by specifying the method type by constructor when creating the request instance.

3. The urlsegment type parameter injects the value into the URL according to the name tag that matches the resource property value, Accountsid is assigned in Twilioapi.execute, and it is the same for each request.

4, we specify where to start the deserialization of the root element name, in this case, the returned XML shape, because the response element does not contain any information related to our defined entity model, so from the next node of the element tree to start deserialization (call node).

We can also define post (and Put/delete/head/options) requests:

 //TwilioApi.cs, method of Twilioapi Classpublic call Initiateoutboundcall (calloptions options) {require.ar Gument ("Caller", options.    Caller); Require.argument ("called", Options.    called); Require.argument ("Url", options.)    URL);    var request = new Restrequest (method.post); Request.    Resource = "Accounts/{accountsid}/calls"; Request.    RootElement = "Calls"; Request. Addparameter ("Caller", options.    Caller); Request. Addparameter ("called", Options.    called); Request. Addparameter ("Url", options.)    URL); if (options. Method.hasvalue) Request. Addparameter ("Method", options.)    Method); if (options. Senddigits.hasvalue ()) request. Addparameter ("Senddigits", options.    Senddigits); if (options. Ifmachine.hasvalue) Request. Addparameter ("Ifmachine", options.    Ifmachine.value); if (options. Timeout.hasvalue) Request. Addparameter ("Timeout", options.)    Timeout.value); return execute<call> (request);}  

This example also proves that Restsharp is a lightweight validation helper that verifies that the submitted parameter values are valid before the request.

The parameter values added by the Addparameter method in the example are submitted in a standard encoding format, similar to a form submitted through a Web page. If it is a GET form request (Get/delete/options/head), the parameter value will be submitted through the query string, and the Addparameter () method can also add header information and cookie parameters. Use the AddObject () method when you are using all properties of an object as arguments. When uploading a file, use the AddFile () method (the request is sent in a variety of encoding formats), and when the request contains the request body (such as XML or JSON), use the Addbody () method.

Iii. Examples of other applications

The following example demonstrates the use of a stream instead of a memory buffer to request content, which is useful in scenarios where large amounts of data are requested and written to disk immediately:

string tempFile = Path.GetTempFileName();using (var writer = File.OpenWrite(tempFile)){    var client = new RestClient(baseUrl);    var request = new RestRequest("Assets/LargeFile.7z");    request.ResponseWriter = (responseStream) => responseStream.CopyTo(writer);    var response = client.DownloadData(request);}
Four, deserialization

Restsharp has a deserializer that handles XML and JSON, and when a response is received, Restclient chooses the appropriate deserializer through the content Type returned by the server. The default settings can be overridden by the content type of the custom setting, which supports the following content type:

    • Application/json-jsondeserializer
    • Application/xml-xmldeserializer
    • Text/json-jsondeserializer
    • Text/xml-xmldeserializer
    • *+json-jsondeserializer (content types using a structured Suffix Syntax specifying JSON)
    • *+xml-xmldeserializer (content types using a structured Suffix Syntax specifying XML)
    • @*@-Xmldeserializer (all other content types not specified)

The default Deserializer attempts to unbind the pain that must parse XML or JSON by mapping CLR entity classes. The entity class defines how the returned data is deserialized. Instead of iterating through the returned data and looking for matching properties in the entity class, restsharp the entity class as a starting point, loops through the accessible writable properties, and finds the corresponding element in the returned data.

Note: The default deserializer does not support dataannotation/datamember, and if you want to use it, you must implement and register your own ideserializer, Ideserializer is wrapping the deserialized library that is compatible with the attributes in the entity class.

For example, the following XML and JSON:

<Person>    <Name>John</Name>    <Id>28</Id></Person>{    "Name": "John",    "Id": 28}

Map the same entity class Person:

public class Person {    public string Name { get; set; }    public int Id { get; set; }}
Supported attribute types (data types): Xmldeserializer:
    • Primitives (int, short, long, etc)
    • Decimal
    • Datetime
    • String
    • Guid
    • List
    • Nested classes
    • Nullable versions of the above listed types
Jsondeserializer
    • Primitives
    • Decimal
    • Datetime
    • String
    • Guid
    • List
    • DICTIONARY<T1, t2>
    • Nested classes
    • Nullable versions of the above listed types
Name matching: Xmldeserializer

When a matching element is found, the default XML deserializer looks for elements and attributes that follow the following order:

    • Absolute Match of element and name
    • lowercase matching of elements and names
    • Name of the camel with the names of the elements match
    • element and name minus underscore and dash match
    • Absolute Match of attribute and name
    • lowercase matching of attributes and names
    • Character and name of camel named match
    • attribute and name minus underline and dash match

You can use the @deserializeas@ attribute to change the name that will be looked up in the property, which is useful if you want to name the property with the names in the XML.

For example:

[DeserializeAs(Name = "forecast_information")]public ForecastInformation Forecast { get; set; }

There is a special case for returning element values, as shown in the following example:

If the XML data is returned as follows:

<Response>Hello world</Response>

There is no way to describe directly in C # classes

public class Response {}

Need something to save the returned element value, in this case, add a Value property:

public class Response{     public string Value { get; set; }}
Jsondeserializer

When finding data for a matching element, the default JSON Deserializer will follow the following order when locating elements:

    • Absolute match with Name
    • Match with name Camel named
    • Match with Name lowercase
    • Matches the name with an underscore (e.g. ProductId, product_id)
    • Matches the name with an underscore lowercase form (e.g. product_id, product_id)

The XML deserializer can change the key mappings with JSON by setting the Deserializeas attribute of the property.

For example:

[DeserializeAs(Name = "forecast_information")]public ForecastInformation Forecast { get; set; }
Collection processing (list/dictionary) Xmldeserializer

Handles two different forms of collections: inline and nested

<?xml version="1.0" encoding="utf-8" ?><InlineListSample>    <image src="1.gif">value1</image>    <image src="2.gif">value2</image>    <image src="3.gif">value3</image>    <image src="4.gif">value4</image></InlineListSample><?xml version="1.0" encoding="utf-8" ?><NestedListSample>   <images>      <image src="1.gif">value1</image>      <image src="2.gif">value2</image>      <image src="3.gif">value3</image>      <image src="4.gif">value4</image>    </images></NestedListSample>

The corresponding C # form is as follows:

public class ListSample{    public List<Image> Images { get; set; }}    public class Image{    public string Src { get; set; }    public string Value { get; set; }}

If two element structures happen to exist simultaneously in the same document, the precedence is in this order: Parented/nested/regular.

Jsondeserializer

Restsharp supports collections (List) and dictionaries (dictionary<string, t>) when mapping JSON arrays and dictionaries

Date processing Xmldeserializer
    • If Restrequest.dateformat has specified the format of the return value, the return value is resolved using the specified format string.
    • If Restrequest.dateformat is not specified, the element value is computed with DateTime.Parse. If the method cannot handle the current format, you need to change the property type to string before processing.
Jsondeserializer

If you do not specify a date format through Restrequest.dateformat, Restsharp attempts to deserialize the properties of the DateTime type in the following format characters (in the order below):

    • "U"
    • "S"
    • "yyyy '-' mm '-' dd ' T ' HH ': ' mm ': ' SS ' Z '"
    • "Yyyy-mm-ddthh:mm:ssz"
    • "Yyyy-mm-dd HH:mm:ssZ"
    • "Yyyy-mm-ddthh:mm:ss"
    • "Yyyy-mm-ddthh:mm:sszzzzzz"

Jsonserializer supports the following JSON date formats by default, and is ignored by default if specific Restrequest.dateformat are specified:

    • iso-1910-09-25t09:30:25z
    • Javascript Date Objects-new Date (-1870352975000)
    • Unix Timestamps-1435206458

For the JS Date object, the time interval based on the JS era is added to the millisecond, which adjusts according to the specified time zone.

Custom override default Deserializer

You can rewrite your own deserializer to process the returned data in the following steps:

    • Create a class to implement the Ideserializer interface at the same time.
    • Register the handler with the Restclient.addhandler (ContentType, Ideserializer) method and associate the content type, if this content type has already been registered, will be overridden by the specified Handker, which can remove all registered handler through the Restclient.clearhandlers () method, or through Restclient.removehandler (ContentType) Remove a handler.
Overriding the default serializer

When using XML or JSON-formatted data as the request body, you can use your own Iserializer:

var request = new RestRequest();request.RequestFormat = DataFormat.Xml;request.XmlSerializer = new SuperXmlSerializer(); // implements ISerializerrequest.AddBody(person); // object serialized to XML using your custom serializer;
Rewrite jsonserializationstrategy

During serialization, trying to support different projection strategies between C # and Jsom will get into trouble, and rewriting Mapclrmembernametojsonfieldname will help:

class SnakeJsonSerializerStrategy : PocoJsonSerializerStrategy{    protected override string MapClrMemberNameToJsonFieldName(string clrPropertyName)    {        //PascalCase to snake_case        return string.Concat(clrPropertyName.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + char.ToLower(x).ToString() : x.ToString()));    }}

Then use it in your code:

SimpleJson.CurrentJsonSerializerStrategy = new SnakeJsonSerializerStrategy();
Five, Certification

Restsharp contains HTTP authentication and can be iauthenticator to complete its own implementation while registering with Restclient:

var client = new RestClient();client.Authenticator = new SuperAuthenticator(); // implements IAuthenticator

When using Restclient.execute or Restclient.execute

Using Simpleauthenticator

Simpleauthenticator allows the user name and password to be passed as a GET or post parameter, depending on the request method used:

var client = new RestClient("http://example.com");client.Authenticator = new SimpleAuthenticator("username", "foo", "password", "bar");var request = new RestRequest("resource", Method.GET);client.Execute(request);

The URL generated by the request should look like this: Http://example.com/resource?username=foo&password=bar

If a put or POST request is used for the above request, the value will be submitted as an encoded form.

Vi. parameter types for restrequest

After you create a new restrequest, you can add parameters to it, with the following 5 types of parameters currently supported and their description of the attributes under the default Ihttp implementation.

Cookies

The parameters added to the list of cookies will be sent separately with the request, the cookie name is the name of the parameter, and the value is the value of the parameter passed. ToString).

Httpheader

The parameters that are added as HTTP headers are sent separately as the request, the header name is the name of the parameter, and the header value is the value of the passed parameter.

Note that some of the restricted headers behave differently or are ignored, and you can view their properties in the _restrictedheaderactions dictionary in Http.cs.

getOrPost

If a GET request is executed, RESTSHARP will append the parameter to the URL in the form: "Url?name1=value1&name2=value2";

If it is a post or a put request, it depends on whether there are files in the request, if not, the parameters are sent in the request body, such as "name1=value1&name2=value2", will be application/ x-www-form-urlencoded format, depending on the request method will have different performance.

In both cases, the parameter name and value are automatically encoded by the URL.

If there are files in the request, RESTSHARP will send the request in multipart/form-data form, and the parameters will be formatted as follows:

Content-Disposition: form-data; name="parameterName"ParameterValue
Urlsegment

Unlike getOrPost, this parameter type uses placeholders in Requesturl instead of values.

var request = new RestRequest("health/{entity}/status");request.AddParameter("entity", "s2", ParameterType.UrlSegment);

When the request is executed, RESTSHARP will attempt to match the placeholder with the parameter name, and the match succeeds with the parameter value instead of the placeholder, the result of which is: "Health/s2/status".

Requestbody

If this parameter is set, the value of the parameter is passed in the requested body mode. The request can only receive one requestbody parameter (the first).

The parameter name will be used as the requested Content-type header.

The Requestbody parameter is not valid for GET or head, and they do not need to send the request body.

If you also have the getOrPost parameter, the parameter overrides Requestbody--restsharp does not merge the parameters, but discards the requestbody parameter.

QueryString

Similar to getOrPost, it always appends the parameter to the URL in the following form: "Url?name1=value1&name2=value2", regardless of the type of request method.

Vii. Cache Automatic Cache management

Restsharp 102.4 + version supports all requests for irestclient instances to share the same System.Net.CookieContainer management, in this way, the responses setting or not setting the cache will be used in subsequent requests. To share the Cookiecontainer, set the properties when you create the restclient:

var client = new RestClient("http://server/");client.CookieContainer = new System.Net.CookieContainer();
Eight, cross-platform support

Restsharp contains 2 versions of Lib:

    • . NET Framework 4.5.2
    • . NET Standard 2.0

means that restsharp can be applied on the following platforms:

    • Windows using the. NET Framework
    • Windows using. NET Core
    • Linux or MAC using Mono
    • Linux or MAC using. NET Core
    • Any and platform that supports Mono 5 or. NET Core 2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.