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 ...
随机推荐
- js中跳转
<li><a href="javascript:recordRescSifting('+subject.subId+');">'+subject.subNa ...
- leetcode Search Insert Position Python
#Given a sorted array and a target value, return the index if the target is found. If #not, return t ...
- Linux学习awk命令
awk是一个强大的文本分析工具,相对于grep的查找,sed的编辑,awk在其对数据分析并生成报告时,显得尤为强大.简单来说awk就是把文件逐行的读入,以空格为默认分隔符将每行切片,切开的部分再进行各 ...
- CFILE追加写入文件
CFile file; file.Open(strName, CFile::modeWrite|CFile::modeNoTruncate|CFile::modeCreate); ) { file.S ...
- python 32位、64位确定
1.python 进入交互式命令行,如下: 2.执行以下命令: import struct;print struct.calcsize("P") * 8
- [转]前端CSS规范整理
一.文件规范 1.文件均归档至约定的目录中. 具体要求通过豆瓣的CSS规范进行讲解: 所有的CSS分为两大类:通用类和业务类.通用的CSS文件,放在如下目录中: 基本样式库 /css/core 通用 ...
- Makefile写法
概述 -- 什么是makefile?或许很多Winodws的程序员都不知道这个东西,因为那些Windows的IDE都为你做了这个工作,但我觉得要作一个好的和professional的程序员,makef ...
- 【Chromium中文文档】跨平台开发的约定与模式
跨平台开发的约定与模式 转载请注明出处:https://ahangchen.gitbooks.io/chromium_doc_zh/content/zh//General_Architecture/C ...
- 关于ODI agent的配置部署
分类: Linux 最近,做了几个ODI项目的部署,发现ODI agent所在的位置对整个E-LT工作的影响还是比较大的,根据Oracle的官方说法,agent一般需要部署在目标端的数据库服务器上,或 ...
- 立体像对DEM提取
版权声明:本教程涉及到的数据仅练习使用,禁止用于商业用途. 目录 1.概述 2.详细操作步骤 第一步:输入立体像对 第二步:定义地面控制点 第三步:定义连接点 第四步:设定DEM提取参数 第五步:输出 ...