1. 程式人生 > >C#呼叫RESTful API

C#呼叫RESTful API

現在很多的網路服務都用RESTful API來實現。比如百度的搜尋推廣API介紹使用Rest原因:REST+JSON風格的API相比SOAP+XML,好處是:呼叫更加靈活,也更容易擴充套件;JSON格式傳輸資訊比XML減少約30%的資料量,效率更高。因此建議開發者使用REST風格的API

利用該文中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 Virgin Mary for inspiration";
string query = "madonna";

StringBuilder data = new StringBuilder();
data.Append("appid=" + HttpUtility.UrlEncode(appId));
data.Append("&context=" + HttpUtility.UrlEncode(context));
data.Append("&query=" + HttpUtility.UrlEncode(query));

// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());

// Set the content length in the request headers
request.ContentLength = byteData.Length;

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

// 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());
}

3、HTTP 驗證請求
有些朋友在呼叫Restful Api時,可能要提供使用者名稱和密碼進行Http身份驗證,這裡我們可以通過為請求增加一個NetworkCredentials例項來完成.

// Create the web request
HttpWebRequest request
= WebRequest.Create("https://api.del.icio.us/v1/posts/recent") as HttpWebRequest;

// Add authentication to request
request.Credentials = new NetworkCredential("username", "password");

// 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());
}