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 ...
随机推荐
- Programming C#.Classes and Objects.传递参数
ref 关键字通过引用(而非值)传递参数. 通过引用传递的效果是,对所调用方法中的参数进行的任何更改都反映在调用方法中. 说明: 不要混淆通过引用传递的概念与引用类型的概念. 这两种概念是不同的. 无 ...
- 怎样在超级终端和PC之间通过串口传输文件
Windows环境下,通过SecureCRT软件,用串口向ARM开发板发送文件: 输入命令 rz,可以看到如下图所示: 选择路径点击上传即可. 如果是想从Arm开发板中把文件Down下来,则可以按照下 ...
- Jdbc初体验
Java数据库连接(JDBC)由一组用 Java 编程语言编写的类和接口组成.JDBC 为工具/数据库开发人员提供了一个标准的 API,使他们能够用纯Java API 来编写数据库应用程序.然而各个开 ...
- Android StrictMode介绍
转:http://www.blueowls.net/android-strictmode%E4%BB%8B%E7%BB%8D/ /** * enables "strict mode" ...
- subline text 3的模版设置
文件目录在这个地方,然后用St3打开,进行模版修改就行了
- 优盘(U 盘) 采用TLC, MLC, SLC芯片 的区别 与使用寿命
最近一直在看大家在讨论sandisk,pny,金士顿等大厂都开始用tlc的芯片问题,让大家基本都不敢用U盘存数据了按照之前的擦写参数TLC 1000次MLC 10000次SL ...
- 计算机世界的道(C/ASM)生一(OS),一生二(API),二生万象(MFC/COM)——学包装技术的程序员将来会损失比较大,因为不了解本质,一旦包装过时就会被淘汰
道生一,一生二,二生万象.OO的思想就是抽象,万象归宗,化繁为简.99%的程序员使用OO,或者所谓的类库的目的就是好用,不必了解内部实现就可以直接达到所期望的结果.这时一种生产力的进步,一种流水线式半 ...
- POJ 2686 Traveling by Stagecoach 壮压DP
大意是有一个人从某个城市要到另一个城市(点数<=30) 然后有n个马车票,相邻的两个城市走的话要消耗掉一个马车票. 花费的时间呢,是马车票上有个速率值,用边/速率就是花的时间. 问最后这个人花费 ...
- Oracle_系统和对象权限管理
授予系统权限: GRANT { system_privilege | role } [,{ system_privilege | role }]... ... TO {user | role | PU ...
- Day4_代码重用与函数
知识点速记: 重用代码的方法:脚本包含require().include(); 全局配置文件php.ini(auto_prepend_file/auto_append_file); 目录配置文件.ht ...