C#實(shí)現(xiàn)訪問(wèn)Web API Url提交數(shù)據(jù)并獲取處理結(jié)果
應(yīng)用場(chǎng)景
應(yīng)用程序編程接口(Application Programming Interface,簡(jiǎn)稱(chēng):API),是服務(wù)方定制開(kāi)發(fā)一些預(yù)先定義的函數(shù)方法,并提供訪問(wèn)的方式及規(guī)則。訪問(wèn) API 的開(kāi)發(fā)人員無(wú)需理解其內(nèi)部工作機(jī)制,只根據(jù)服務(wù)方提供的說(shuō)明及規(guī)則,提交參數(shù)數(shù)據(jù),并獲取有需要的處理結(jié)果。
Web API 是 Web 服務(wù)器和 Web 瀏覽器之間的應(yīng)用程序處理接口。我們常見(jiàn)的模式是訪問(wèn) Web API Url 地址,POST 或 GET 所需要的參數(shù)數(shù)據(jù),并獲取 Json 、XML或其它指定格式的處理結(jié)果。
范例運(yùn)行環(huán)境
操作系統(tǒng): Windows Server 2019 DataCenter
.net版本: .netFramework4.0 或以上
開(kāi)發(fā)工具:VS2019 C#
WebService 類(lèi)
設(shè)計(jì)
WebService 類(lèi)的 GetResponseResult 方法提供了訪問(wèn) Web API Url 的能力,方法返回字符串(即API返回的處理結(jié)果),另外WebService 類(lèi)還提供了 ErrorMessage 屬性,通過(guò)訪問(wèn)此屬性是否為空以判斷方法是否正確返回了處理結(jié)果,GetResponseResult方法的 使用說(shuō)明見(jiàn)如下表格:
| 序號(hào) | 參數(shù)名 | 類(lèi)型 | 說(shuō)明 |
|---|---|---|---|
| 1 | url | string | 要訪問(wèn)的URL地址 |
| 2 | encoding | System.Text.Encoding | 字符編碼格式 |
| 3 | method | string | 提交的方法類(lèi)型,如 "POST","GET" |
| 4 | postData | string | 提交的數(shù)據(jù)包 |
| 5 | headers | string[] | 傳遞請(qǐng)求頭的字符串?dāng)?shù)組,如: string[] headers = new string[] {"key1:value1","key2:value2" }; 其中每一項(xiàng)的關(guān)鍵名和關(guān)鍵值用冒號(hào)分隔 |
| 6 | ContentType | string | 內(nèi)容類(lèi)型,默認(rèn)為 ContentType= "application/x-www-form-urlencoded" |
實(shí)現(xiàn)
實(shí)現(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)備請(qǐng)求...
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ā)送請(qǐng)求并獲取相應(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("訪問(wèn)沒(méi)有成功,錯(cuò)誤信息:"+ErrorMessage);
}else{
Response.Write(resultStr);
}其它
我們?cè)?WebService 類(lèi)里創(chuàng)建了另一個(gè)實(shí)用方法:DownLoadFile,即提供對(duì)應(yīng)的下載地址可以指定下載到本地文件,方法返回字符串(為空表示下載成功,不為空則顯示錯(cuò)誤信息)方法的使用說(shuō)明見(jiàn)如下表格:
| 序號(hào) | 參數(shù)名 | 類(lèi)型 | 說(shuō)明 |
|---|---|---|---|
| 1 | url | string | 要下載的URL地址 |
| 2 | localfile | string | 要保存的本地完整路徑地址 |
實(shí)現(xiàn)代碼如下:
public string DownLoadFile(string url, string localfile)
{
string pathUrl = url;
System.Net.HttpWebRequest request = null;
System.Net.HttpWebResponse response = null;
//請(qǐng)求網(wǎng)絡(luò)路徑地址
request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(pathUrl);
request.Timeout = 5000; // 超時(shí)時(shí)間
//獲得請(qǐng)求結(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#實(shí)現(xiàn)訪問(wèn)Web API Url提交數(shù)據(jù)并獲取處理結(jié)果的文章就介紹到這了,更多相關(guān)C#訪問(wèn)Web API Url數(shù)據(jù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
講解C#面相對(duì)象編程中的類(lèi)與對(duì)象的特性與概念
這篇文章主要介紹了C#面相對(duì)象編程中的類(lèi)與對(duì)象的特性與概念,OOP面向?qū)ο笳Z(yǔ)言相對(duì)C語(yǔ)言這樣面相過(guò)程的語(yǔ)言來(lái)說(shuō)具有類(lèi)和對(duì)象以及方法這樣的特性,需要的朋友可以參考下2016-01-01
c# 服務(wù)器上傳木馬監(jiān)控代碼(包含可疑文件)
c# 監(jiān)控服務(wù)器上傳木馬(包含可疑文件)2010-05-05

