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
- Simple GET Requests
- Simple POST Requests
- HTTP Authenticated Requests
- Error Handling
- Further Reading
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
- using System;
- using System.IO;
- using System.Net;
- using System.Text;
- // Create the web request
- HttpWebRequest request = WebRequest.Create("http://developer.yahoo.com/") as HttpWebRequest;
- // Get response
- using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
- {
- // Get the response stream
- StreamReader reader = new StreamReader(response.GetResponseStream());
- // Console application output
- Console.WriteLine(reader.ReadToEnd());
- }
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
- // We use the HttpUtility class from the System.Web namespace
- using System.Web;
- Uri address = new Uri("http://api.search.yahoo.com/ContentAnalysisService/V1/termExtraction");
- // Create the web request
- HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
- // Set type to POST
- request.Method = "POST";
- request.ContentType = "application/x-www-form-urlencoded";
- // Create the data we want to send
- string appId = "YahooDemo";
- string context = "Italian sculptors and painters of the renaissance"
- + "favored the Virgin Mary for inspiration";
- string query = "madonna";
- StringBuilder data = new StringBuilder();
- data.Append("appid=" + HttpUtility.UrlEncode(appId));
- data.Append("&context=" + HttpUtility.UrlEncode(context));
- data.Append("&query=" + HttpUtility.UrlEncode(query));
- // Create a byte array of the data we want to send
- byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
- // Set the content length in the request headers
- request.ContentLength = byteData.Length;
- // Write data
- using (Stream postStream = request.GetRequestStream())
- {
- postStream.Write(byteData, 0, byteData.Length);
- }
- // Get response
- using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
- {
- // Get the response stream
- StreamReader reader = new StreamReader(response.GetResponseStream());
- // Console application output
- Console.WriteLine(reader.ReadToEnd());
- }
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
- // Create the web request
- HttpWebRequest request
- = WebRequest.Create("https://api.del.icio.us/v1/posts/recent") as HttpWebRequest;
- // Add authentication to request
- request.Credentials = new NetworkCredential("username", "password");
- // Get response
- using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
- {
- // Get the response stream
- StreamReader reader = new StreamReader(response.GetResponseStream());
- // Console application output
- Console.WriteLine(reader.ReadToEnd());
- }
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
- public static void PrintSource(Uri address)
- {
- HttpWebRequest request;
- HttpWebResponse response = null;
- StreamReader reader;
- StringBuilder sbSource;
- if (address == null) { throw new ArgumentNullException("address"); }
- try
- {
- // Create and initialize the web request
- request = WebRequest.Create(address) as HttpWebRequest;
- request.UserAgent = ".NET Sample";
- request.KeepAlive = false;
- // Set timeout to 15 seconds
- request.Timeout = 15 * 1000;
- // Get response
- response = request.GetResponse() as HttpWebResponse;
- if (request.HaveResponse == true && response != null)
- {
- // Get the response stream
- reader = new StreamReader(response.GetResponseStream());
- // Read it into a StringBuilder
- sbSource = new StringBuilder(reader.ReadToEnd());
- // Console application output
- Console.WriteLine(sbSource.ToString());
- }
- }
- catch (WebException wex)
- {
- // This exception will be raised if the server didn't return 200 - OK
- // Try to retrieve more information about the network error
- if (wex.Response != null)
- {
- using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)
- {
- Console.WriteLine(
- "The server returned '{0}' with the status code {1} ({2:d}).",
- errorResponse.StatusDescription, errorResponse.StatusCode,
- errorResponse.StatusCode);
- }
- }
- }
- finally
- {
- if (response != null) { response.Close(); }
- }
- }
Further reading
Related information on the web.
Make Yahoo! Web Service REST Calls With C#的更多相关文章
- [转]Web Service Authentication
本文转自:http://www.codeproject.com/Articles/9348/Web-Service-Authentication Download source files - 45. ...
- [转]Calling Web Service Functions Asynchronously from a Web Page 异步调用WebServices
本文转自:http://www.codeproject.com/Articles/70441/Calling-Web-Service-Functions-Asynchronously-from Ove ...
- 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& ...
- Summary of Amazon Marketplace Web Service
Overview Here I want to summarize Amazon marketplace web service (MWS or AMWS) that can be used for ...
- REST和SOAP Web Service的区别比较
本文转载自他人的博客,ArcGIS Server 推出了 对 SOAP 和 REST两种接口(用接口类型也许并不准确)类型的支持,本文非常清晰的比较了SOAP和Rest的区别联系! ///////// ...
- 转:Web service是什么?
作者: 阮一峰 我认为,下一代互联网软件将建立在Web service(也就是"云")的基础上. 我把学习笔记和学习心得,放到网志上,欢迎指正. 今天先写一个最基本的问题,Web ...
- 【转载】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 ...
- 转-Web Service中三种发送接受协议SOAP、http get、http post
原文链接:web服务中三种发送接受协议SOAP/HTTP GET/HTTP POST 一.web服务中三种发送接受协议SOAP/HTTP GET/HTTP POST 在web服务中,有三种可供选择的发 ...
- C# Web Service 初级教学
原文连接:http://www.codeproject.com/cs/webservices/myservice.asp作者:Chris Maunder Introduction Creating y ...
随机推荐
- Invalid signature file digest for Manifest main attributes
Solving a Spark error: Invalid signature file digest for Manifest main attributes When using spark-s ...
- [Python]豆瓣用户读书短评下载工具
简介 朋友问我能不能做一个下载他在豆瓣读书上的短评的工具,于是就做了这个“豆瓣用户读书短评下载工具”. GitHub链接:https://github.com/xiaff/dbc-downloader ...
- 非阻塞IO
设置描述符非阻塞的两种方法: 1,调用 open 时,设置,O_NONBLOCK; 2,调用 fcntl设置: 具体如下: ,open("/xxx/file1",O_RDWR|O_ ...
- 关于继承UITableViewController若干问题
// // MSHomeCommentTableViewController.m // xiaoqu-ios // // Created by Charlie on 15/7/1. // Copyri ...
- atoi函数和atof函数
1.函数名:atoi 功能:是把字符串转换成整型数的一个函数,应用在计算机程序和办公软件中 名字来源:alphanumeric to integer 用法:int atoi(const char *n ...
- android ViewHolder 使用
android中使用ListView ExpandableListView 数据适配器adapter很多都是自己定义,自己定义数据适配器时,要重写getView.重写getView为了不让每次调 ...
- C++中的句柄类
初次在<C++ Primer>看到句柄,不是特别理解.在搜索相关资料后,终于有了点头绪. 首先明白句柄要解决什么问题.参考文章<C++ 沉思录>阅读笔记——代理类 场景: 我们 ...
- dg rman
- E=MC2 - 搜搜百科
E=MC2 - 搜搜百科 1 E=MC2 质能等价理论是爱因斯坦狭义相对论的最重要的推论,即著名的方程式E=mC^2,式中E为能量,m为质量,C为光速:也就是说,一切物质都潜藏着质量乘于光速平方的能量 ...
- 茴香豆的第五种写法---设置ExpandableListView系统自带图标按下效果
1 编写groupindicator_selector.xml如下: <?xml version="1.0" encoding="utf-8"?> ...