Core code extraction for interaction between clients (Windows applications and web) and Web APIs
//★HTTP request object. Httprequestmessage requestmsg = new httprequestmessage (); // set the Data Type of the HTTP request to jsonrequestmsg. headers. accept. add (New mediatypewithqualityheadervalue ("application/JSON"); // request data link (URI) for example: "http://10.186.3.xx/zl_server/api/#controller#/[id]? Xxx = xxx &... "requestmsg. requesturi = new uri (strtorequest );//★HTTP Content Object httpcontent content = NULL; If (objtosend! = NULL) // stringcontent (): converts the string-based HTTP content. // Jsonconvert. serializeobject (objtosend): serialize an object to jsoncontent = new stringcontent (jsonconvert. serializeobject (objtosend), encoding. utf8, "application/JSON"); requestmsg. method = httpmethod. get; // get data requestmsg. content = content ;//★HTTP client object (used to send HTTP requests and receive HTTP responses) Static readonly httpclient s_httpclient = new httpclient (); // s_httpclient is the httpclient object: used to send HTTP requests and receive HTTP responses // s_httpclient.sendasync: sends an HTTP request for an asynchronous operation and returns the response. Task
Code for client (Windows application and web) Interaction with Web APIs
// Get call method (set list) to obtain a single piece of data, you only need to add "/ID" webapiclienthelper. dojsonrequest <simuser_api_get> ("http: // 10.186.3.21/zl_server/API/entrance", enuhttpmethod. get); // post call method (new) webapiclienthelper. dojsonrequest <usbdisk_api_post> ("http: // 10.186.3.21/zl_server/API/entrance", enuhttpmethod. post, objtosend: objtopost); // put call method (Change) webapiclienthelper. dojsonrequest <user_api_put> ("http: // 10.186.3.21/zl_server/API/entrance/2", enuhttpmethod. put, objtosend: userput, TICK: uservm. updateticks );
/// <Summary> // interaction function between the client and the API service /// </Summary> /// <typeparam name = "T"> T dojsonrequest <t> "T" is a variable parameter, is based on the input type can be model class or ienumerable <t> </typeparam> // <Param name = "struri"> request address </param> // /<Param name = "method"> request type (get, put, post, delete) </param> /// <Param name = "querycondition"> paging parameters </param> /// <Param name = "objtosend"> object parameters (usually used during update) </param> /// <Param name = "tick"> change time </param> /// <returns> </Returns> Public static t dojsonrequest <t> (string struri, enuhttpmethod method, iuriconvertable querycondition = NULL, object objtosend = NULL, long tick = 0) {string strtorequest = struri; if (tick! = 0 & (Method = enuhttpmethod. Put | Method = enuhttpmethod. delete) strtorequest + = "? Updateticks = "+ tick. tostring (cultureinfo. invariantculture); // cultureinfo. invariantculture is used to set the format of IF (querycondition! = NULL & Method = enuhttpmethod. Get) strtorequest + = querycondition. querystring; // indicates an HTTP request message. Httprequestmessage requestmsg = new httprequestmessage (); // this step is asymmetric encryption makeprincipleheader (requestmsg, strtorequest); // set the Data Type of the HTTP request to JSON requestmsg. headers. accept. add (New mediatypewithqualityheadervalue ("application/JSON"); // request data link (URI) requestmsg. requesturi = new uri (strtorequest); httpcontent content = NULL; If (objtosend! = NULL) // stringcontent (): converts the string-based HTTP content. // Jsonconvert. serializeobject (objtosend): serialize an object to JSON content = new stringcontent (jsonconvert. serializeobject (objtosend), encoding. utf8, "application/JSON"); Switch (method) {Case enuhttpmethod. post: requestmsg. method = httpmethod. post; // post is used to add requestmsg. content = content; break; Case enuhttpmethod. put: requestmsg. method = httpmethod. put; // put is used to modify requestmsg. content = content; break; Case enu Httpmethod. delete: requestmsg. method = httpmethod. delete; break; default: // enuhttpmethod. get: requestmsg. method = httpmethod. get; // get is used to get break;} // s_httpclient is the httpclient object: used to send HTTP requests and receive HTTP responses // s_httpclient.sendasync: sends an HTTP request for an asynchronous operation, and return the response. Task // This step is the key request submission process, rtnall. result is actually a multi-threaded processing, yes. one of the new features of Net Framework 4.0, resultmessage = rtnall. result;} catch (aggresponexception AE) {foreach (VAR ex in AE. innerexceptions) {If (ex is httprequestexception) {Throw new njtcsexception ("failed to send network request", ex) ;}} if (! Resultmessage. issuccessstatuscode) // determines whether the response is successful? {Task <njthttpinfo> error; try {/** resultmessage. content. readasasync <njthttpinfo> (s_formatters) How to understand? * Explanation: reads data from the response content asynchronously and assigns the value to the specified model object * s_formatters: New mediatypeformatter [] {New jsonmediatypeformatter ()} format the specified data in JSON format */error = resultmessage. content. readasasync <njthttpinfo> (s_formatters);} catch (exception ex) {Throw new njtcsexception ("Server Unexpected error", ex);} Throw new njtcsexception (error. result. message);} If (method! = Enuhttpmethod. get) {return default (t); // default (t): return NULL (except for the get method, values need to be obtained, and no response results need to be returned in other methods )} try {/*★This step is critical to assigning the data returned by the server to the local machine. * How to understand resultmessage. content. readasasync <njthttpinfo> (s_formatters? * Explanation: reads data from the response content asynchronously and assigns the value to the specified model object * s_formatters: New mediatypeformatter [] {New jsonmediatypeformatter ()} format the specified data in JSON format */rtnfinal = resultmessage. content. readasasync <t> (s_formatters);} catch (exception ex) {Throw new njtcsexception ("server return and request mismatch", ex);} catch (njtcsexception njtex) {njtex. parameterobject = new {uri = struri, method = method, Data = objtosend, tick = tick}; throw ;}# endregion return rtnfinal. result ;}