如何使用C#調用雅虎REST服務

 .NET Framework提供類處理HTTP請求。這篇文章講述一下處理GET和POST請求。

概述

簡單GET請求

簡單POST請求

HTTP授權請求

錯誤處理

深入閱讀


概述

System.Net命名空間包含 HttpWebRequest和 HttpWebResponse類,這兩個類可以從web服務器獲取數據和使用基於HTTP的服務。通常你需要添加System.Web的引用,這樣就可以使用HttpUtility類,這個類可以提供方法對 HTML 和URL的文本進行編碼或者解碼。

雅虎web服務返回XML數據。有些web服務返回其他格式的數據,比如JSON和序列化的PHP,.NET Framework自從擴展支持處理xml數據之後,處理這種格式的數據就特別簡單了。

簡單GET請求

接下來的例子獲取網頁並打印出源碼。

C# GET 例1

using System;  
using System.IO;  
using System.Net;  
using System.Text;  
  
// Create the web request  
HttpWebRequest request = WebRequest.Create("https://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());  
}  

簡單POST請求
有些APIs要求你使用POST請求。爲了實現這個功能,我們改變請求方法和內容類型,然後將請求的數據寫入到數據流(stream)中。

C# POST例1

// We use the HttpUtility class from the System.Web namespace  
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());  
}  

HTTP授權請求
del.icio.us API要求你使用授權的請求,使用HTTP授權傳遞用戶名和密碼。這個很容易實現的,只要在請求的時候增加NetworkCredentials 就可以了。

C# HTTP AUTHENTICATION


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

錯誤處理
雅虎提供衆多基於REST的web服務,不全是使用相同的錯誤處理方式。有些web服務返回狀態碼200(表示OK),詳細的錯誤信息在返回來的xml裏面,但是有些web服務使用標準的HTTP狀態碼錶示錯誤信息。請閱讀您使用的web服務的文檔,瞭解你所遇到的響應的錯誤類型。請記住,雅虎基於瀏覽器授權和HTTP授權是不一樣的。調用 HttpRequest.GetResponse() 方法在服務器沒有返回狀態碼200(表示OK),請求超時和網絡錯誤的時候,會引發錯誤。但是,重定向會自動處理的。
這是一個典型的例子,打印一個網頁的內容和基本的HTTP錯誤代碼處理錯誤。

C# GET 例2

public static void PrintSource(Uri address)  
{  
    HttpWebRequest request;  
    HttpWebResponse response = null;  
    StreamReader reader;  
    StringBuilder sbSource;  
  
    if (address == null) { throw new ArgumentNullException("address"); }  
  
    try  
    {  
        // Create and initialize the web request  
        request = WebRequest.Create(address) as HttpWebRequest;  
        request.UserAgent = ".NET Sample";  
        request.KeepAlive = false;  
        // Set timeout to 15 seconds  
        request.Timeout = 15 * 1000;  
  
        // Get response  
        response = request.GetResponse() as HttpWebResponse;  
  
        if (request.HaveResponse == true && response != null)  
        {  
            // Get the response stream  
            reader = new StreamReader(response.GetResponseStream());  
  
            // Read it into a StringBuilder  
            sbSource = new StringBuilder(reader.ReadToEnd());  
  
            // Console application output  
            Console.WriteLine(sbSource.ToString());  
        }  
    }  
    catch (WebException wex)  
    {  
        // This exception will be raised if the server didn't return 200 - OK  
        // Try to retrieve more information about the network error  
        if (wex.Response != null)  
        {  
            using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)  
            {  
                Console.WriteLine(  
                    "The server returned '{0}' with the status code {1} ({2:d}).",  
                    errorResponse.StatusDescription, errorResponse.StatusCode,  
                    errorResponse.StatusCode);  
            }  
        }  
    }  
    finally  
    {  
        if (response != null) { response.Close(); }  
    }  
}  

深入閱讀

網上相關信息。
翻譯這篇文章其實是自己想學習如何使用C#調用REST服務。

發佈了50 篇原創文章 · 獲贊 6 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章