Make Yahoo! Web Service REST Calls With C#

简介: 原文 http://developer.yahoo.com/dotnet/howto-rest_cs.html The .NET Framework provides classes for performing HTTP requests.

原文 http://developer.yahoo.com/dotnet/howto-rest_cs.html

The .NET Framework provides classes for performing HTTP requests. This HOWTO describes how to perform both GET and POST requests.

Overview

The System.Net namespace contains the HttpWebRequest and HttpWebResponse classes which fetch data from web servers and HTTP based web services. Often you will also want to add a reference to System.Web which will give you access to the HttpUtility class that provides methods to HTML and URL encode and decode text strings.

Yahoo! Web Services return XML data. While some web services can also return the data in other formats, such as JSON and Serialized PHP, it is easiest to utilize XML since the .NET Framework has extensive support for reading and manipulating data in this format.

Simple GET Requests

The following example retrieves a web page and prints out the source.

C# GET Sample 1

  1. using System;  
  2. using System.IO;  
  3. using System.Net;  
  4. using System.Text;  
  5.   
  6. // Create the web request  
  7. HttpWebRequest request = WebRequest.Create("http://developer.yahoo.com/"as HttpWebRequest;  
  8.   
  9. // Get response  
  10. using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)  
  11. {  
  12.     // Get the response stream  
  13.     StreamReader reader = new StreamReader(response.GetResponseStream());  
  14.   
  15.     // Console application output  
  16.     Console.WriteLine(reader.ReadToEnd());  
  17. }  

Simple POST Requests

Some APIs require you to make POST requests. To accomplish this we change the request method and content type and then write the data into a stream that is sent with the request.

C# POST Sample 1

  1. // We use the HttpUtility class from the System.Web namespace  
  2. using System.Web;  
  3.   
  4. Uri address = new Uri("http://api.search.yahoo.com/ContentAnalysisService/V1/termExtraction");  
  5.   
  6. // Create the web request  
  7. HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;  
  8.   
  9. // Set type to POST  
  10. request.Method = "POST";  
  11. request.ContentType = "application/x-www-form-urlencoded";  
  12.   
  13. // Create the data we want to send  
  14. string appId = "YahooDemo";  
  15. string context = "Italian sculptors and painters of the renaissance"  
  16.                     + "favored the Virgin Mary for inspiration";  
  17. string query = "madonna";  
  18.   
  19. StringBuilder data = new StringBuilder();  
  20. data.Append("appid=" + HttpUtility.UrlEncode(appId));  
  21. data.Append("&context=" + HttpUtility.UrlEncode(context));  
  22. data.Append("&query=" + HttpUtility.UrlEncode(query));  
  23.   
  24. // Create a byte array of the data we want to send  
  25. byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());  
  26.   
  27. // Set the content length in the request headers  
  28. request.ContentLength = byteData.Length;  
  29.   
  30. // Write data  
  31. using (Stream postStream = request.GetRequestStream())  
  32. {  
  33.     postStream.Write(byteData, 0, byteData.Length);  
  34. }  
  35.   
  36. // Get response  
  37. using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)  
  38. {  
  39.     // Get the response stream  
  40.     StreamReader reader = new StreamReader(response.GetResponseStream());  
  41.   
  42.     // Console application output  
  43.     Console.WriteLine(reader.ReadToEnd());  
  44. }  

HTTP Authenticated requests

The del.icio.us API requires you to make authenticated requests, passing your del.icio.us username and password using HTTP authentication. This is easily accomplished by adding an instance of NetworkCredentials to the request.

C# HTTP Authentication

  1. // Create the web request  
  2. HttpWebRequest request   
  3.     = WebRequest.Create("https://api.del.icio.us/v1/posts/recent"as HttpWebRequest;  
  4.   
  5. // Add authentication to request  
  6. request.Credentials = new NetworkCredential("username""password");  
  7.   
  8. // Get response  
  9. using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)  
  10. {  
  11.     // Get the response stream  
  12.     StreamReader reader = new StreamReader(response.GetResponseStream());  
  13.   
  14.     // Console application output  
  15.     Console.WriteLine(reader.ReadToEnd());  
  16. }  

Error Handling

Yahoo! offers many REST based web services but they don't all use the same error handling. Some web services return status code 200 (OK) and a detailed error message in the returned XML data while others return a standard HTTP status code to indicate an error. Please read the documentation for the web services you are using to see what type of error response you should expect. Remember that HTTP Authentication is different from the Yahoo! Browser-Based Authentication.

Calling HttpRequest.GetResponse() will raise an exception if the server does not return the status code 200 (OK), the request times out or there is a network error. Redirects are, however, handled automatically.

Here is a more full featured sample method that prints the contents of a web page and has basic error handling for HTTP error codes.

C# GET Sample 2

  1. public static void PrintSource(Uri address)  
  2. {  
  3.     HttpWebRequest request;  
  4.     HttpWebResponse response = null;  
  5.     StreamReader reader;  
  6.     StringBuilder sbSource;  
  7.   
  8.     if (address == null) { throw new ArgumentNullException("address"); }  
  9.   
  10.     try  
  11.     {  
  12.         // Create and initialize the web request  
  13.         request = WebRequest.Create(address) as HttpWebRequest;  
  14.         request.UserAgent = ".NET Sample";  
  15.         request.KeepAlive = false;  
  16.         // Set timeout to 15 seconds  
  17.         request.Timeout = 15 * 1000;  
  18.   
  19.         // Get response  
  20.         response = request.GetResponse() as HttpWebResponse;  
  21.   
  22.         if (request.HaveResponse == true && response != null)  
  23.         {  
  24.             // Get the response stream  
  25.             reader = new StreamReader(response.GetResponseStream());  
  26.   
  27.             // Read it into a StringBuilder  
  28.             sbSource = new StringBuilder(reader.ReadToEnd());  
  29.   
  30.             // Console application output  
  31.             Console.WriteLine(sbSource.ToString());  
  32.         }  
  33.     }  
  34.     catch (WebException wex)  
  35.     {  
  36.         // This exception will be raised if the server didn't return 200 - OK  
  37.         // Try to retrieve more information about the network error  
  38.         if (wex.Response != null)  
  39.         {  
  40.             using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)  
  41.             {  
  42.                 Console.WriteLine(  
  43.                     "The server returned '{0}' with the status code {1} ({2:d}).",  
  44.                     errorResponse.StatusDescription, errorResponse.StatusCode,  
  45.                     errorResponse.StatusCode);  
  46.             }  
  47.         }  
  48.     }  
  49.     finally  
  50.     {  
  51.         if (response != null) { response.Close(); }  
  52.     }  
  53. }  

Further reading

Related information on the web.

 

目录
打赏
0
0
0
0
216
分享
相关文章
|
3月前
|
C# 一分钟浅谈:GraphQL 与 REST 比较
本文对比了REST和GraphQL两种流行的API设计风格,从概念、优缺点及C#实现角度进行了详细分析,并提供了代码示例。REST以其简单易懂和无状态特性著称,而GraphQL则通过精确获取和单次请求的优势,提高了数据获取效率。文章还讨论了常见问题与解决策略,帮助开发者根据实际需求选择合适的API设计风格。
75 10
|
5月前
|
异步轮询 Web API 的实现与 C# 示例
异步轮询 Web API 的实现与 C# 示例
131 0
Uno Platform 入门超详细指南:从零开始教你打造兼容 Web、Windows、iOS 和 Android 的跨平台应用,轻松掌握 XAML 与 C# 开发技巧,快速上手示例代码助你迈出第一步
【8月更文挑战第31天】Uno Platform 是一个基于 Microsoft .NET 的开源框架,支持使用 C# 和 XAML 构建跨平台应用,适用于 Web(WebAssembly)、Windows、Linux、macOS、iOS 和 Android。它允许开发者共享几乎全部的业务逻辑和 UI 代码,同时保持原生性能。选择 Uno Platform 可以统一开发体验,减少代码重复,降低开发成本。安装时需先配置好 Visual Studio 或 Visual Studio for Mac,并通过 NuGet 或官网下载工具包。
710 0
C#开发者的新天地:Blazor如何颠覆传统Web开发,打造下一代交互式UI?
【8月更文挑战第28天】Blazor 是 .NET 生态中的革命性框架,允许使用 C# 和 .NET 构建交互式 Web UI,替代传统 JavaScript。本文通过问答形式深入探讨 Blazor 的基本概念、优势及应用场景,并指导如何开始使用 Blazor。Blazor 支持代码共享、强类型检查和丰富的生态系统,简化 Web 开发流程。通过简单的命令即可创建 Blazor 应用,并利用其组件化和数据绑定特性快速搭建界面。无论对于 .NET 还是 Web 开发者,Blazor 都是一个值得尝试的新选择。
373 1
Visual Studio C# 多环境配置 Web.config
Visual Studio C# 多环境配置 Web.config
87 0
使用VB.NET构建Web服务和REST API的指南
【7月更文挑战第2天】使用VB.NET构建Web服务和REST API的指南:从Web服务基础到ASP.NET Core实践,涵盖控制器、路由、模型绑定、安全措施(如JWT、HTTPS)及测试、部署(Azure、Docker)与监控工具。了解如何利用VB.NET在现代云环境中创建高效、安全的API。开始你的VB.NET Web服务开发之旅!**
305 1
Rest风格WEB服务(Rest Style Web Service)的真相
Rest风格WEB服务(Rest Style Web Service)的真相
193 1
C#/ASP.NET应用程序配置文件app.config/web.config的增、删、改操作
C#/ASP.NET应用程序配置文件app.config/web.config的增、删、改操作
105 1
C# Web控件与数据感应之 TreeView 类
C# Web控件与数据感应之 TreeView 类
C# Web控件与数据感应之 CheckBoxList 类
C# Web控件与数据感应之 CheckBoxList 类