原文 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. // Create the web request
  6. HttpWebRequest request = WebRequest.Create("http://developer.yahoo.com/") as HttpWebRequest;
  7. // Get response
  8. using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
  9. {
  10. // Get the response stream
  11. StreamReader reader = new StreamReader(response.GetResponseStream());
  12. // Console application output
  13. Console.WriteLine(reader.ReadToEnd());
  14. }

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

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. // Add authentication to request
  5. request.Credentials = new NetworkCredential("username", "password");
  6. // Get response
  7. using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
  8. {
  9. // Get the response stream
  10. StreamReader reader = new StreamReader(response.GetResponseStream());
  11. // Console application output
  12. Console.WriteLine(reader.ReadToEnd());
  13. }

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

Further reading

Related information on the web.

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

  1. [转]Web Service Authentication

    本文转自:http://www.codeproject.com/Articles/9348/Web-Service-Authentication Download source files - 45. ...

  2. [转]Calling Web Service Functions Asynchronously from a Web Page 异步调用WebServices

    本文转自:http://www.codeproject.com/Articles/70441/Calling-Web-Service-Functions-Asynchronously-from Ove ...

  3. Using UTL_DBWS to Make a Database 11g Callout to a Document Style Web Service

    In this Document   _afrLoop=100180147230187&id=841183.1&displayIndex=2&_afrWindowMode=0& ...

  4. Summary of Amazon Marketplace Web Service

    Overview Here I want to summarize Amazon marketplace web service (MWS or AMWS) that can be used for ...

  5. REST和SOAP Web Service的区别比较

    本文转载自他人的博客,ArcGIS Server 推出了 对 SOAP 和 REST两种接口(用接口类型也许并不准确)类型的支持,本文非常清晰的比较了SOAP和Rest的区别联系! ///////// ...

  6. 转:Web service是什么?

    作者: 阮一峰 我认为,下一代互联网软件将建立在Web service(也就是"云")的基础上. 我把学习笔记和学习心得,放到网志上,欢迎指正. 今天先写一个最基本的问题,Web ...

  7. 【转载】Using the Web Service Callbacks in the .NET Application

    来源 This article describes a .NET Application model driven by the Web Services using the Virtual Web ...

  8. 转-Web Service中三种发送接受协议SOAP、http get、http post

    原文链接:web服务中三种发送接受协议SOAP/HTTP GET/HTTP POST 一.web服务中三种发送接受协议SOAP/HTTP GET/HTTP POST 在web服务中,有三种可供选择的发 ...

  9. C# Web Service 初级教学

    原文连接:http://www.codeproject.com/cs/webservices/myservice.asp作者:Chris Maunder Introduction Creating y ...

随机推荐

  1. jquery 自动调整图片大小

    <script type="text/javascript"> $(document).ready(function(){ $('#cons img').each(fu ...

  2. 轻量级的数据交换语言(JSON)

    游戏开发过程中,很多用到JSON的地方:客户端与服务端的网络通信,程序读取客户端的数值表之类的. JSON用于描述数据结构,有以下形式存在. 对象(object):一个对象以“{”开始,并以“}”结束 ...

  3. C/C++中的far和near两个指针

    Dos 的设计是基于16位的CPU的,也就是CPU中的每个寄存器(Register)只有16位,只能存放0-65535(64K)的值.为了能访问大于64K的内存,人们用了分段的方法,用两个16位的数来 ...

  4. C#学习日志 day7 --------------LINQ与Lamda语句的初步尝试以及XML的生成

    LINQ是一种集成在计算机语言里的信息查询语句,是c#3.0中最惹人瞩目的功能. 在C#中,LINQ语句有两种写法. 第一种写法与SQL语句类似: IEnumerable<Customer> ...

  5. WebService之Axis2

    写在前面 本文只说Axis2的用法. 1.下载与部署 需要下载两个文件: 下载地址:http://mirrors.cnnic.cn/apache/axis/axis2/java/core/1.7.1/ ...

  6. MYSQL 用户

    MYSQL 并没有与SQL Server一样的两个级别的主体,它只有user. user 的信息都保存在mysql 数据库的 user 表中:我想也可以用insert 的方式新建用户,只是这种尝试还没 ...

  7. CDC变更数据捕获

    CDC变更数据捕获 (2013-03-20 15:25:52)   分类: SQL SQL Server中记录数据变更的四个方法:触发器.Output子句.变更数据捕获(Change Data Cap ...

  8. J2SE知识点摘记(二十六)

    为了用“集合框架”的额外部分把排序支持添加到 Java 2 SDK,版本 1.2,核心 Java 库作了许多更改.像 String 和 Integer 类如今实现 Comparable 接口以提供自然 ...

  9. OA项目之打印

    打印 若此页有一个打印按钮: <input type="button" id="btnPrint" class="button_sm7" ...

  10. nodejs开发微信1——微信路由设置a(access_token和tickets)

    /* jshint -W079 */ /* jshint -W020 */ "use strict"; var _ = require("lodash"); v ...