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 ...
随机推荐
- 学习使用GitHub(一)--之入门
因为经常Windows和linux系统交替的使用,在实验室一台电脑,在家一台电脑,自己的电脑和实验室的电脑上面的代码往往没法同步,以前由于种种原因(其实就是懒,没有学习GitHub这样的代码管理工具) ...
- 关于html标签元素的data-*属性
关于这个主题的文章和博客其实已经非常多了,这里并非要重复造轮子,只是看到一些例子稍微有点麻烦,其实也很简单,但是对于一个刚刚入门的人,w3c的例子甚至可能看不懂,这里列出一个最简单不过的小案例以供参考 ...
- Android RelativeLayout常用属性介绍
下面介绍一下RelativeLayout用到的一些重要的属性: 第一类:属性值为true或false android:layout_centerHrizontal 水平居中 android:layou ...
- 【JQ成长笔记】jQuery cookie的使用
jquery cookie挺好用的.简单实在.菜鸟都能用得上..额.文笔不好不好..咳咳.. 先来看看jq.cookie的aip 写入cookie $.cookie("this-cookie ...
- codeforces 659E . New Reform 强连通
题目链接 对于每一个联通块, 如果有一个强连通分量, 那么这个联通块对答案的贡献就是0. 否则对答案贡献是1. #include <iostream> #include <vecto ...
- Activity之间定时跳转
起源:很多应用在打开时,首先会加载欢迎页面,经过几秒后再跳转到主页面. 下面,我通过两种不同的方式来实现页面的定时跳转. 第一种方式: 通过Timer类的schedule方法. 实现从MainActi ...
- centos下添加的端口不能访问(防火墙关闭)
最近遇到一个郁闷的问题.好几天都没解决,求助,谢谢大家. 打算开放一个端口15900.可是无论怎么设置防火墙,或者干脆关闭防火墙.就是不能被外部机器访问(在同一内网网段机器). 本机访问没有问题(12 ...
- Android中pendingIntent的深入理解
pendingIntent字面意义:等待的,未决定的Intent.要得到一个pendingIntent对象,使用方法类的静态方法 getActivity(Context, int, Intent, i ...
- Java HashSet和LinkedHashSet的用法
Java HashSet和LinkedHashSet的用法 类HashSet和LinkedHashSet都是接口Set的实现,两者都不能保存重复的数据.主要区别是HashSet不保证集合中元素的顺序, ...
- 将外部准备好的sqlite导入到项目当中
首先,将sqlite数据库文件放在Resource文件夹下,并且允许其编译到项目当中. 之后在AppDelegate当中执行一些代码,这里将代码封装了一个Helper: #import "R ...