C#實現(xiàn)訪問Web API Url提交數(shù)據(jù)并獲取處理結(jié)果
應(yīng)用場景
應(yīng)用程序編程接口(Application Programming Interface,簡稱:API),是服務(wù)方定制開發(fā)一些預(yù)先定義的函數(shù)方法,并提供訪問的方式及規(guī)則。訪問 API 的開發(fā)人員無需理解其內(nèi)部工作機(jī)制,只根據(jù)服務(wù)方提供的說明及規(guī)則,提交參數(shù)數(shù)據(jù),并獲取有需要的處理結(jié)果。
Web API 是 Web 服務(wù)器和 Web 瀏覽器之間的應(yīng)用程序處理接口。我們常見的模式是訪問 Web API Url 地址,POST 或 GET 所需要的參數(shù)數(shù)據(jù),并獲取 Json 、XML或其它指定格式的處理結(jié)果。
范例運(yùn)行環(huán)境
操作系統(tǒng): Windows Server 2019 DataCenter
.net版本: .netFramework4.0 或以上
開發(fā)工具:VS2019 C#
WebService 類
設(shè)計
WebService 類的 GetResponseResult 方法提供了訪問 Web API Url 的能力,方法返回字符串(即API返回的處理結(jié)果),另外WebService 類還提供了 ErrorMessage 屬性,通過訪問此屬性是否為空以判斷方法是否正確返回了處理結(jié)果,GetResponseResult方法的 使用說明見如下表格:
序號 | 參數(shù)名 | 類型 | 說明 |
---|---|---|---|
1 | url | string | 要訪問的URL地址 |
2 | encoding | System.Text.Encoding | 字符編碼格式 |
3 | method | string | 提交的方法類型,如 "POST","GET" |
4 | postData | string | 提交的數(shù)據(jù)包 |
5 | headers | string[] | 傳遞請求頭的字符串?dāng)?shù)組,如: string[] headers = new string[] {"key1:value1","key2:value2" }; 其中每一項的關(guān)鍵名和關(guān)鍵值用冒號分隔 |
6 | ContentType | string | 內(nèi)容類型,默認(rèn)為 ContentType= "application/x-www-form-urlencoded" |
實現(xiàn)
實現(xiàn)代碼如下:
public sealed class WebService { public string ErrorMessage = ""; public string GetResponseResult(string url, System.Text.Encoding encoding, string method, string postData) { return GetResponseResult(url,encoding,method,postData,null); } public string GetResponseResult(string url, System.Text.Encoding encoding, string method, string postData,string[] headers,string ContentType= "application/x-www-form-urlencoded") { method = method.ToUpper(); System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12; if (method == "GET") { try { WebRequest request2 = WebRequest.Create(@url); request2.Method = method; WebResponse response2 = request2.GetResponse(); Stream stream = response2.GetResponseStream(); StreamReader reader = new StreamReader(stream, encoding); string content = reader.ReadToEnd(); return content; } catch (Exception ex) { ErrorMessage = ex.Message; return ""; } } Stream outstream = null; Stream instream = null; StreamReader sr = null; HttpWebResponse response = null; HttpWebRequest request = null; byte[] data = encoding.GetBytes(postData); // 準(zhǔn)備請求... try { // 設(shè)置參數(shù) request = WebRequest.Create(url) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = method; request.Timeout = 1000000; if (headers != null) { for(int i = 0; i < headers.GetLength(0); i++) { if (headers[i].Split(':').Length <2) { continue; } if (headers[i].Split(':').Length > 1) { if (headers[i].Split(':')[0] == "Host") { request.Host = headers[i].Split(':')[1]; continue; }else if (headers[i].Split(':')[0] == "Content-Type") { request.ContentType = headers[i].Split(':')[1]; continue; } } request.Headers.Add(headers[i]); } } request.ContentType = ContentType; request.ContentLength = data.Length; outstream = request.GetRequestStream(); outstream.Write(data, 0, data.Length); outstream.Close(); //發(fā)送請求并獲取相應(yīng)回應(yīng)數(shù)據(jù) response = request.GetResponse() as HttpWebResponse; instream = response.GetResponseStream(); sr = new StreamReader(instream, encoding); string content = sr.ReadToEnd(); sr.Close(); sr.Dispose(); return content; } catch (Exception ex) { ErrorMessage = ex.Message; return ""; } }//get response result }
調(diào)用
調(diào)用示例代碼如下:
string content = "{\"key1\": 1,\"key2\": \"value2\"}"; string apiUrl = "https://api.t.com/test.aspx"; WebService ws = new WebService(); string resultStr = ws.GetResponseResult(settingUrl, Encoding.UTF8, "POST", content); if(ErrorMessage!=""){ Response.Write("訪問沒有成功,錯誤信息:"+ErrorMessage); }else{ Response.Write(resultStr); }
其它
我們在 WebService 類里創(chuàng)建了另一個實用方法:DownLoadFile,即提供對應(yīng)的下載地址可以指定下載到本地文件,方法返回字符串(為空表示下載成功,不為空則顯示錯誤信息)方法的使用說明見如下表格:
序號 | 參數(shù)名 | 類型 | 說明 |
---|---|---|---|
1 | url | string | 要下載的URL地址 |
2 | localfile | string | 要保存的本地完整路徑地址 |
實現(xiàn)代碼如下:
public string DownLoadFile(string url, string localfile) { string pathUrl = url; System.Net.HttpWebRequest request = null; System.Net.HttpWebResponse response = null; //請求網(wǎng)絡(luò)路徑地址 request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(pathUrl); request.Timeout = 5000; // 超時時間 //獲得請求結(jié)果 try { response = (System.Net.HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); //先創(chuàng)建文件 Stream sos = new System.IO.FileStream(localfile, System.IO.FileMode.Create); byte[] img = new byte[1024]; int total = stream.Read(img, 0, img.Length); while (total > 0) { //之后再輸出內(nèi)容 sos.Write(img, 0, total); total = stream.Read(img, 0, img.Length); } stream.Close(); stream.Dispose(); sos.Close(); sos.Dispose(); return ""; } catch (Exception e) { return e.Message; } }
到此這篇關(guān)于C#實現(xiàn)訪問Web API Url提交數(shù)據(jù)并獲取處理結(jié)果的文章就介紹到這了,更多相關(guān)C#訪問Web API Url數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
c# 服務(wù)器上傳木馬監(jiān)控代碼(包含可疑文件)
c# 監(jiān)控服務(wù)器上傳木馬(包含可疑文件)2010-05-05