如何使用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服务。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值