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. 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.

 

时间: 2024-11-01 01:48:54

Make Yahoo! Web Service REST Calls With C#的相关文章

在ASP.NET Atlas中调用Web Service—批量调用以提高效率

asp.net|web 对于Atlas程序,在某些情况下,我们需要在短时间内调用大量的Web Service,例如某个列表中用户快速的点击删除.这时网络带宽,稳定程度等等往往会造成较长时间的延迟.如果可以将这些调用包装成一个单一的请求,那么用户只需忍受一次网络延迟,即可得到处理的结果,也间接的提高了效率.似乎这并不是一个很容易实现的功能,但幸运的是,Atlas中内建了对批量调用Web Service的支持,您所需要的只是在程序中简单设置一下. Atlas中每个Web Service的调用请求都有

在ASP.NET Atlas中调用Web Service

asp.net|web 在前一篇文章(在ASP.NET Atlas中调用Web Service--创建Mashup调用远端Web Service(基础知识以及简单示例))中,我介绍了一些Atlas中对远程Web Service进行Mashup的基础知识,并给出了一个最基础的没有丝毫用处例子.今天再回到这个话题上,我将给出一个更复杂点的,但有一些用处的例子--Yahoo! Weather. 废话到此为止,让我们先熟悉一下Yahoo! Weather服务:Yahoo!在其网站上提供了天气预报服务(h

Developing An Image Upload Web Service

web Developing An Image Upload Web Service By: Bipin JoshiLevel: IntermediatePosted Date: 5/31/2002Tested with ASP.NET v1.0 (RTM) Click for Printable Version Click here to download sample code Member Rating: 3.90 (Rated by 10 members) Rate This Item

Using ASP.NET Session State in a Web Service

asp.net|session|web Quick Overview of ASP.NET SessionsASP.NET session state is maintained by using one of two underlying mechanisms. The first is by using HTTP cookies. The idea behind HTTP cookies is that when the client sends a request, the server

使用Google的Web Service

google|web 一.简介 Google搜索引擎提供了基于SOAP的Web Service.这意味着不同的开发语言.开发环境都能够使用这种服务,另外,Google为了简化Java程序员的开发,它还提供了一套Java API接口,用于访问Web Serivce,这使得开发一套支持Google搜索功能的程序变得十分容易.开发人员可以将Google的搜索功能嵌入到他们的应用程序当中.本文将介绍如何使用这些Java API,以及如何使用google的Web Service. 目前,Google的AP

简单理解Web Service三种实现方式

  Web Service概念: 根据W3C的定义,Web服务(Web service)应当是一个软件系统,用以支持网络间不同机器的互动操作.网络服务通常是许多应用程序接口(API)所组成的,它们通过网络的远程服务器端,执行客户所提交服务的请求.简单的来说就是服务器端向客户端提供服务. Web Service实现方式: (1)远程过程调用(RPC) RPC协议就是为了解决不同的客户端跨平台的访问服务器而产生的,最初的Web Service都是采用RPC部署,它是一种通过网络从远程计算机程序上请求

《SOA Web Service合约设计与版本化》目录—导读

版权声明 SOA Web Service合约设计与版本化 Authorized translation from the English language edition, entitled Web Service Contract Design and Versioning for SOA, 978-0136135173 by Thomas Erl, Anish Karmarkar, Priscilla Walmsley, Hugo Haas, Umit Yalcinalp, Canyang

Web Service随笔1

Web Service随笔.1 为什么出现Web Service?现在Internet的发展十分迅速,它从前的框架是"人来获取网络上的资源,比如:程序.文档等".也就是说,现在的Web是以人为中心的,人来发送各种请求.而它的发展趋势将是主体从"人"转向"程序",比如媒体播放器.浏览器等,也就是说"以应用程序中心"的Web.其实,在Web Service出现之前,人们就已经在做这方面的事情了,例如Java的Servlet和CGI

Jersey : Java规范下REST风格Web Service开发框架

Sun正在致力于的建立RESt风格Web服务的规范,  规范如下  JSRs: Java Specification RequestsJSR 311: JAX-RS: The JavaTM API for RESTful Web Services链接:http://jcp.org/en/jsr/detail?id=311而同时该规范的参考实现Jersery也在逐渐成熟,目前已经是0.7版,大家可以参考https://jersey.dev.java.net/. 从JAX-RS规范和Jersey的发