欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#實現(xiàn)訪問Web API Url提交數(shù)據(jù)并獲取處理結(jié)果

 更新時間:2024年05月23日 09:30:08   作者:初九之潛龍勿用  
Web API  是 Web 服務(wù)器和 Web 瀏覽器之間的應(yīng)用程序處理接口,我們常見的模式是訪問 Web API Url 地址,并獲取 Json 、XML或其它指定格式的處理結(jié)果, 本文我們介紹了使用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ù)名類型說明
1urlstring

要訪問的URL地址

2encodingSystem.Text.Encoding字符編碼格式
3methodstring提交的方法類型,如 "POST","GET"
4postDatastring

提交的數(shù)據(jù)包

5headersstring[]

傳遞請求頭的字符串?dāng)?shù)組,如:

string[] headers = new string[] {"key1:value1","key2:value2" };

其中每一項的關(guān)鍵名和關(guān)鍵值用冒號分隔

6ContentTypestring內(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ù)名類型說明
1urlstring

要下載的URL地址

2localfilestring要保存的本地完整路徑地址

實現(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#實現(xiàn)在Word中更改字體顏色

    利用C#實現(xiàn)在Word中更改字體顏色

    在日常工作中,我們有時會需要修改字體的顏色來突出文本重點,讓讀者更容易抓住文章要點。在今天這篇文章中,我將為大家介紹如何以編程方式,在Word更改字體顏色,感興趣的可以了解一下
    2023-02-02
  • 講解C#面相對象編程中的類與對象的特性與概念

    講解C#面相對象編程中的類與對象的特性與概念

    這篇文章主要介紹了C#面相對象編程中的類與對象的特性與概念,OOP面向?qū)ο笳Z言相對C語言這樣面相過程的語言來說具有類和對象以及方法這樣的特性,需要的朋友可以參考下
    2016-01-01
  • C#中的char與string詳解

    C#中的char與string詳解

    本文詳細(xì)講解了C#中的char與string,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-01-01
  • c# 服務(wù)器上傳木馬監(jiān)控代碼(包含可疑文件)

    c# 服務(wù)器上傳木馬監(jiān)控代碼(包含可疑文件)

    c# 監(jiān)控服務(wù)器上傳木馬(包含可疑文件)
    2010-05-05
  • C#獲取程序文件相關(guān)信息的方法

    C#獲取程序文件相關(guān)信息的方法

    這篇文章主要介紹了C#獲取程序文件相關(guān)信息的方法,可實現(xiàn)獲取程序版本號、版權(quán)聲明、程序文本信息等,需要的朋友可以參考下
    2014-09-09
  • C#中的預(yù)定義類型與引用類型

    C#中的預(yù)定義類型與引用類型

    這篇文章介紹了C#中的預(yù)定義類型與引用類型,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-05-05
  • C# 文件拖拽和pixturBox縮放與拖拽功能

    C# 文件拖拽和pixturBox縮放與拖拽功能

    這篇文章主要介紹了C# 文件拖拽和pixturBox縮放與拖拽功能,代碼簡單易懂,非常不錯具有參考借鑒價值,需要的朋友可以參考下
    2017-10-10
  • 詳解C#如何讀寫config配置文件

    詳解C#如何讀寫config配置文件

    這篇文章主要介紹了詳解C#如何讀寫config配置文件,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-12-12
  • C#中String.PadRight方法的具體使用

    C#中String.PadRight方法的具體使用

    本文主要介紹了C#中String.PadRight方法的具體使用, 返回一個指定長度的新字符串,其中在當(dāng)前字符串的結(jié)尾填充空格或指定的Unicode字符,下面就來詳細(xì)的了解一下
    2024-01-01
  • C#圖片按比例縮放的實現(xiàn)代碼

    C#圖片按比例縮放的實現(xiàn)代碼

    這篇文章主要介紹了C#圖片按比例縮放的實現(xiàn)代碼,有需要的朋友可以參考一下
    2014-01-01

最新評論