C#調用RESTful API


如今非常多的網絡服務都用RESTful API來實現。

比方百度的搜索推廣API介紹使用Rest原因:REST+JSON風格的API相比SOAP+XML,優點是:調用更加靈活。也更easy擴展;JSON格式傳輸信息比XML降低約30%的數據量,效率更高。因此建議開發人員使用REST風格的API

查找了非常多調用Rest API網絡碎片資料,總是無法理解或者生效。

以下摘一點認為有效果的作為參考吧。

http://www.makeyuan.com/2014/02/27/1117.html

利用該文中Post方法來調用百度搜索推廣的API。盡管代碼亂。可是總算成功了,以下即是代碼:

        public static void send()
        {
            string url = "https://api.baidu.com/json/sms/v3/AccountService/getAccountInfo";
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/json";
            string data = "{\n\"header\": {\n\"token\": \"30xxx6aaxxx93ac8cxx8668xx39xxxx\",\n\"username\": \"jdads\",\n\"password\": \"liuqiangdong2010\",\n\"action\": \"\"\n},\n\"body\": {}\n}";

            byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
            request.ContentLength = byteData.Length;

            using(Stream postStream = request.GetRequestStream())
            {
                postStream.Write(byteData, 0, byteData.Length);
            }

            using(HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                Console.WriteLine(reader.ReadToEnd());
            }
        }

通過執行,發現json數據部分。當之前沒有換行符的時候。使用@表示字符串並雙引號用兩個來表示時。會報數據錯誤。

附上鏈接的文章的幾種調用方式:
1、以Get方式獲取

using System;
using System.IO;
using System.Net;
using System.Text;

// Create the web request
HttpWebRequest request = WebRequest.Create("http://developer.yahoo.com/") as HttpWebRequest;

// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());

// Console application output
Console.WriteLine(reader.ReadToEnd());
}

2、以Post方式獲取

using System.Web;

Uri address = new Uri("http://api.search.yahoo.com/ContentAnalysisService/V1/termExtraction");

// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;

// Set type to POST
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";

// Create the data we want to send
string appId = "YahooDemo";
string context = "Italian sculptors and painters of the renaissance"
+ "favored the Vir 
posted @ 2017-05-07 08:04  zsychanpin  閱讀( 16028)  評論( 0編輯  收藏


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM