最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#實(shí)現(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#實(shí)現(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"

實(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)備請求...
            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)建了另一個實(shí)用方法:DownLoadFile,即提供對應(yīng)的下載地址可以指定下載到本地文件,方法返回字符串(為空表示下載成功,不為空則顯示錯誤信息)方法的使用說明見如下表格:

序號參數(shù)名類型說明
1urlstring

要下載的URL地址

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

實(shí)現(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#實(shí)現(xiàn)訪問Web API Url提交數(shù)據(jù)并獲取處理結(jié)果的文章就介紹到這了,更多相關(guān)C#訪問Web API Url數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • C#索引器簡單實(shí)例代碼

    C#索引器簡單實(shí)例代碼

    打開.Net Framework源代碼隨便看幾個類,就會發(fā)現(xiàn)索引器的影子。索引器可以被重載,可以接收一個或者多個參數(shù),但是不可以定義為靜態(tài)的。可以用關(guān)聯(lián)數(shù)組的方式訪問索引器。
    2013-03-03
  • 詳解WPF中的對象資源

    詳解WPF中的對象資源

    這篇文章主要介紹了WPF中對象資源的相關(guān)資料,幫助大家更好的理解和學(xué)習(xí)使用WPF,感興趣的朋友可以了解下
    2021-04-04
  • C#連接SQL?Sever數(shù)據(jù)庫詳細(xì)圖文教程

    C#連接SQL?Sever數(shù)據(jù)庫詳細(xì)圖文教程

    C#是Microsoft公司為.NET Framework推出的重量級語言,和它搭配最完美的數(shù)據(jù)庫無疑就是Microsoft SQL Server了,下面這篇文章主要給大家介紹了關(guān)于C#連接SQL?Sever數(shù)據(jù)庫的詳細(xì)圖文教程,需要的朋友可以參考下
    2023-06-06
  • c# 文件操作(移動,復(fù)制,重命名)

    c# 文件操作(移動,復(fù)制,重命名)

    這篇文章主要介紹了c# 如何對文件操作(移動,復(fù)制,重命名),幫助大家更好的理解和使用c#,感興趣的朋友可以了解下
    2020-12-12
  • C#獲取Word文檔中所有表格的實(shí)現(xiàn)代碼分享

    C#獲取Word文檔中所有表格的實(shí)現(xiàn)代碼分享

    這篇文章主要介紹了C#獲取Word文檔中所有表格的實(shí)現(xiàn)代碼分享,小編親測可用,需要的朋友可以參考下
    2014-09-09
  • C#如何操作Excel數(shù)據(jù)透視表

    C#如何操作Excel數(shù)據(jù)透視表

    這篇文章主要為大家詳細(xì)介紹了C#如何操作Excel數(shù)據(jù)透視表, 創(chuàng)建透視表、設(shè)置行折疊、展開等操作,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-04-04
  • C# 創(chuàng)建高精度定時器的示例

    C# 創(chuàng)建高精度定時器的示例

    這篇文章主要介紹了C# 創(chuàng)建高精度定時器的示例,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下
    2021-02-02
  • C#入門之定義類成員與接口實(shí)現(xiàn)

    C#入門之定義類成員與接口實(shí)現(xiàn)

    這篇文章介紹了C#入門之定義類成員與接口實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-05-05
  • 淺談c#.net中巧用ToString()將日期轉(zhuǎn)成想要的格式

    淺談c#.net中巧用ToString()將日期轉(zhuǎn)成想要的格式

    有時候我們要對時間進(jìn)行轉(zhuǎn)換,達(dá)到不同的顯示效果,更多的該怎么辦呢?
    2013-03-03
  • c# 如何實(shí)現(xiàn)獲取二維數(shù)組的列數(shù)

    c# 如何實(shí)現(xiàn)獲取二維數(shù)組的列數(shù)

    這篇文章主要介紹了c# 實(shí)現(xiàn)獲取二維數(shù)組的列數(shù)操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-04-04

最新評論

晴隆县| 永春县| 招远市| 秦皇岛市| 高雄市| 屏山县| 琼海市| 库车县| 安远县| 綦江县| 澄城县| 成安县| 娱乐| 南华县| 克拉玛依市| 海晏县| 黄平县| 石狮市| 靖宇县| 巴彦淖尔市| 星子县| 华宁县| 咸丰县| 牟定县| 五常市| 万山特区| 大安市| 自治县| 岱山县| 会宁县| 漾濞| 万载县| 吉木萨尔县| 潮安县| 雷州市| 西畴县| 榕江县| 东源县| 岱山县| 紫云| 峨眉山市|