原文 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. onload ready

    确保在 <body> 元素的onload事件中没有注册函数,否则不会触发$(document).ready()事件. 可以在同一个页面中无限次地使用$(document).ready()事 ...

  2. java.util.List org.apache.struts2.components.Form.getValidators(java.lang.String) threw an exception

    在使用ajax主题时出现上述错误的解决办法是将form表单中的action属性值改为*.action后就可以解决.至于为什么会这样不太明白.但是修改action的属性值以后就会出现另一个错误即 对应的 ...

  3. QQ在线咨询状态显示不出来怎么办?http://bizapp.qq.com/webpres.htm

  4. SiKuli 图形脚本语言【转载】

    Sikuli 是一种新颖的图形脚本语言,或者说是一种另类的自动化测试技术.它与我们常用的自动化测试技术(工具)有很大的区别. 当你看到上图sikuli的脚本时,一定会惊呼,这样都可以~!脚本加截图~~ ...

  5. N沟道增强型MOS管双向低频开关电路

    MOS-N 场效应管 双向电平转换电路 -- 适用于低频信号电平转换的简单应用 如上图所示,是 MOS-N 场效应管 双向电平转换电路.双向传输原理: 为了方便讲述,定义 3.3V 为 A 端,5.0 ...

  6. 转:web前端面试题合集 (Javascript相关)(js异步加载详解)

    1. HTTP协议的状态消息都有哪些? 1**:请求收到,继续处理2**:操作成功收到,分析.接受3**:完成此请求必须进一步处理4**:请求包含一个错误语法或不能完成5**:服务器执行一个完全有效请 ...

  7. ulimit 说明

    ulimit官方描述 Provides control over the resources available to the shell and to processes started by it ...

  8. HDU 5727 Necklace(二分图匹配)

    [题目链接]http://acm.hdu.edu.cn/showproblem.php?pid=5727 [题目大意] 现在有n颗阴珠子和n颗阳珠子,将它们阴阳相间圆排列构成一个环,已知有些阴珠子和阳 ...

  9. java学习之匿名内部类与包装类

    匿名内部类: 所谓匿名内部类,顾名思义指的就是定义在类内部的匿名类,现有的spring框架开发以及java图形界面都经常用到匿名内部类. 下面来看一个代码: interface A{ public v ...

  10. dataGuard client 自动切换

    使用dataguard作为HA方案,要解决的一个问题在于:后台数据库发生了切换,client连接如何做到自动切到新的primary数据库上? 如果做通用的方案,需要客户端自己提供自动重连的能力,这点大 ...