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.

 

目录
相关文章
|
Web App开发
Blackhat 2009 Make Money on the web the black hat way
PPT可以再官方下载 这里放出Video blackhat 2008年的了   http://www.
548 0
|
4月前
|
XML Java 应用服务中间件
WebService - Axis2基于JAX-WS开发WebService并发布多个WebService
WebService - Axis2基于JAX-WS开发WebService并发布多个WebService
36 0
|
4月前
|
Java 应用服务中间件 Spring
WebService - Axis2使用services.xml进行开发server与client(未与Spring整合)
WebService - Axis2使用services.xml进行开发server与client(未与Spring整合)
44 0