Application scenarios
Application Programming Interface (API) is a service provider that customizes and develops some predefined functions and methods and provides access methods and rules. Developers who access the API do not need to understand their internal working mechanisms. They only submit parameter data based on the instructions and rules provided by the service provider and obtain the required processing results.
The Web API is an application processing interface between a web server and a web browser. Our common pattern is to access the parameter data required by the Web API Url address, POST or GET, and obtain processing results in Json, XML, or other specified formats.
Sample operating environment
Operating system: Windows Server 2019 DataCenter
.net version: .netFramework 4.0 or above
Development Tools: VS2019 C#
WebService Class
design
The GetResponseResult method of the WebService class provides the ability to access the Web API URL. The method returns a string (that is, the processing result returned by the API). In addition, the WebService class also provides the ErrorMessage property. By accessing whether this property is empty, it is to determine whether the method returns the processing result correctly. The instructions for the use of the GetResponseResult method are shown in the following table:
Serial number | Parameter name | type | illustrate |
---|---|---|---|
1 | url | string | URL to access |
2 | encoding | Character encoding format | |
3 | method | string | Submitted method types, such as "POST", "GET" |
4 | postData | string | Submitted packets |
5 | headers | string[] |
Pass the string array of request headers, such as: string[] headers = new string[] {"key1:value1","key2:value2" }; The key names and key values of each item are separated by a colon |
6 | ContentType | string | Content type, default is ContentType= "application/x-www-form-urlencoded" |
accomplish
The implementation code is as follows:
public sealed class WebService { public string ErrorMessage = ""; public string GetResponseResult(string url, encoding, string method, string postData) { return GetResponseResult(url,encoding,method,postData,null); } public string GetResponseResult(string url, encoding, string method, string postData,string[] headers,string ContentType= "application/x-www-form-urlencoded") { method = (); = | .Tls11 | .Tls12; if (method == "GET") { try { WebRequest request2 = (@url); = method; WebResponse response2 = (); Stream stream = (); StreamReader reader = new StreamReader(stream, encoding); string content = (); return content; } catch (Exception ex) { ErrorMessage = ; return ""; } } Stream outstream = null; Stream instream = null; StreamReader sr = null; HttpWebResponse response = null; HttpWebRequest request = null; byte[] data = (postData); // Prepare for request... try { // Set parameters request = (url) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); = cookieContainer; = true; = method; = 1000000; if (headers != null) { for(int i = 0; i < (0); i++) { if (headers[i].Split(':').Length <2) { continue; } if (headers[i].Split(':').Length > 1) { if (headers[i].Split(':')[0] == "Host") { = headers[i].Split(':')[1]; continue; }else if (headers[i].Split(':')[0] == "Content-Type") { = headers[i].Split(':')[1]; continue; } } (headers[i]); } } = ContentType; = ; outstream = (); (data, 0, ); (); //Send a request and get the corresponding response data response = () as HttpWebResponse; instream = (); sr = new StreamReader(instream, encoding); string content = (); (); (); return content; } catch (Exception ex) { ErrorMessage = ; return ""; } }//get response result }
Call
The call sample code is as follows:
string content = "{\"key1\": 1,\"key2\": \"value2\"}"; string apiUrl = "/"; WebService ws = new WebService(); string resultStr = (settingUrl, Encoding.UTF8, "POST", content); if(ErrorMessage!=""){ ("The access was not successful, error message:"+ErrorMessage); }else{ (resultStr); }
other
We have created another practical method in the WebService class: DownloadFile, which provides the corresponding download address and can specify the download to the local file. The method returns a string (empty means the download is successful, and if it is not empty, the error message will be displayed). The instructions for using the method are shown in the following table:
Serial number | Parameter name | type | illustrate |
---|---|---|---|
1 | url | string | URL to download |
2 | localfile | string | The local full path address to save |
The implementation code is as follows:
public string DownLoadFile(string url, string localfile) { string pathUrl = url; request = null; response = null; //Request the network path address request = ()(pathUrl); = 5000; // Timeout time //Get request result try { response = ()(); Stream stream = (); //Create the file first Stream sos = new (localfile, ); byte[] img = new byte[1024]; int total = (img, 0, ); while (total > 0) { //Open contents later (img, 0, total); total = (img, 0, ); } (); (); (); (); return ""; } catch (Exception e) { return ; } }
This is the article about C# accessing Web API Url to submit data and obtain processing results. For more related C# accessing Web API Url data, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!