原文 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. CGI version1.1-第一章 介绍 (译)

    CGI version1.1-第一章 介绍 1.简介 1.1 用途 CGI 是为 HTTP服务器 与 CGI脚本 在 响应客户端请求分配职责, 客户请求由url,方法与关于传输协议的附属信息, CGI ...

  2. Python封装的访问MySQL数据库的类及DEMO

    # Filename:mysql_class.py # Author:Rain.Zen; Date: 2014-04-15 import MySQLdb class MyDb: '''初始化[类似于构 ...

  3. Ajax中XML和JSON格式的优劣比较

    刚做完一个小的使用Ajax的项目.整个小项目使用JavaScript做客户端,使用PHP做服务器端.利用xmlHttpRequest组件作为交互工具,利用XML作为数据传输的格式.做完后基本做一个简单 ...

  4. this的用法this.name=name 这个什么意思

    public Employee(string name, string alias){ // Use this to qualify the fields, name and alias: this. ...

  5. s3c6410学习笔记-烧写uboot+构建文件系统

    一.进入目录 #cd u-boot-1.1.6_sndk6410 二.SD卡 make clean make distclean vim Makefile                       ...

  6. 得到IP包的数据意义(简单实现例子)

    #include <stdio.h> #include <unistd.h> #include <linux/if_ether.h> #include <li ...

  7. SD和SDHC和SDXC卡的区别是什么

    SD卡,SDHC卡,SDXC卡区别在规格不一样,SD卡最大支持2GB容量,SDHC 最大支持32GB容量,SDXC 最大支持2TB(2048GB)容量,支持SDXC卡的数码设备是兼容支持SD卡与SDH ...

  8. 柯南君:看大数据时代下的IT架构(3)消息队列之RabbitMQ-安装、配置与监控

    柯南君:看大数据时代下的IT架构(3)消息队列之RabbitMQ-安装.配置与监控 一.安装 1.安装Erlang 1)系统编译环境(这里采用linux/unix 环境) ① 安装环境 虚拟机:VMw ...

  9. discuz函数quote

    public static function quote($str, $noarray = false) { if (is_string($str)) return '\'' . addcslashe ...

  10. nodejs上传图片模块做法;

    服务端代码: var express = require('express'); var swig = require('swig'); //1.引入multer模块 var multer = req ...