如何使用C#调用雅虎REST服务
.NET Framework提供类处理HTTP请求。这篇文章讲述一下处理GET和POST请求。
概述
简单GET请求
简单POST请求
HTTP授权请求
错误处理
深入阅读
概述
System.Net命名空间包含 HttpWebRequest和
HttpWebResponse
类,这两个类可以从web服务器获取数据和使用基于HTTP的服务。通常你需要添加System.Web的引用,这样就可以使用
HttpUtility类,这个类可以提供方法对 HTML 和URL的文本进行编码或者解码。
雅虎web服务返回XML数据。有些web服务返回其他格式的数据,比如JSON和序列化的PHP,.NET Framework自从扩展支持处理xml数据之后,处理这种格式的数据就特别简单了。
简单GET请求
接下来的例子获取网页并打印出源码。
C# GET 例1
using System;
using System.IO;
using System.Net;
using System.Text; // Create the web request
HttpWebRequest request = WebRequest.Create("https://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());
}
简单POST请求
C# POST例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授权请求
NetworkCredentials
就可以了。
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());
}
错误处理
HttpRequest.GetResponse()
方法在服务器没有返回状态码200(表示OK),请求超时和网络错误的时候,会引发错误。但是,重定向会自动处理的。
C# GET 例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(); } }
}
深入阅读
- HttpWebRequest 类 文档
- HttpWebResponse 类 文档
- A Deeper Look at Performing HTTP Requests in an ASP.NET Page
- .NET Screen Scraping in depth
翻译这篇文章其实是自己想学习如何使用C#调用REST服务。
如何使用C#调用雅虎REST服务相关推荐
- SOCKET是调用操作系统通信服务的一种机制
有没有SOCKET,网卡都会接收数据.网卡工作在数据链路层,它只认识链路上邻近的点.它甚至不认识它隔壁的隔壁,它又怎么可能知道传输层的信息呢(起点与终点,是传输层的信息)?...传输层的信息,只能由传 ...
- 提交响应后无法调用sendredirect_微服务的那些事(三),微服务的远程调用方式。RPC和HTTP...
2.远程调用方式 无论是微服务还是SOA,都面临着服务间的远程调用.那么服务间的远程调用方式有哪些呢? 常见的远程调用方式有以下几种: RPC:Remote Produce Call远程过程调用,类似 ...
- 实现远程调用_微服务的那些事(三),微服务的远程调用方式。RPC和HTTP
2.远程调用方式 无论是微服务还是SOA,都面临着服务间的远程调用.那么服务间的远程调用方式有哪些呢? 常见的远程调用方式有以下几种: RPC:Remote Produce Call远程过程调用,类似 ...
- JAVA与.NET的相互调用——通过Web服务实现相互调用
JAVA与.NET是现今世界竞争激烈的两大开发媒体,两者语言有很多相似的地方.而在很多大型的开发项目里面,往往需要使用两种语言进行集成开发.而很多的开发人员都会偏向于其中一种语言,在使用集成开发的时候 ...
- 【spring boot】使用RestTemplate调用百度坐标转换服务
前言 spring boot 2.0.0.RELEASE http://api.map.baidu.com/geoconv/v1/?coords=114.21892734521,29.57542977 ...
- 小程序微信授权登录服务器异常,解决调试腾讯云微信小程序Demo错误“登录失败:调用鉴权服务失败#40029_WEIXIN_CODE_ERR”...
此文章解决大家有可能遇到的"登录失败:调用鉴权服务失败#40029的问题"~~ 很多人出现上面的问题,那是因为:如果在购买解决方案时,把AppId 和 AppSecret 填写错误 ...
- feign调用多个服务_Spring Cloud 快速入门系列之feign–微服务之间的调用
我们将一个大的应用拆成多个小的服务之后,紧接着的一个问题就是,原本都在一个项目里,方法我可以随便调用,但是拆开后,原来的方法就没法直接调用了,这时候要怎么办? Spring Cloud提供了feign ...
- js调用python接口_JavaScript如何调用Python后端服务
欢迎关注[无量测试之道]公众号,回复[领取资源], Python编程学习资源干货. Python+Appium框架APP的UI自动化. Python+Selenium框架Web的UI自动化. Pyth ...
- SpringCloud 入门教程(六): 用声明式REST客户端Feign调用远端HTTP服务
首先简单解释一下什么是声明式实现? 要做一件事, 需要知道三个要素,where, what, how.即在哪里( where)用什么办法(how)做什么(what).什么时候做(when)我们纳入ho ...
最新文章
- .net简单算法实现无限级分类(一)
- APP的CPU,内存,耗电,流量测试工具
- 2021年度 Egon Balas 奖得主:达摩院印卧涛
- 浅谈(Java)AIO-异步IO
- 编程器测试软件,CH341A编程器
- 【转】自动化专业十大看家课程
- linux中#和## 用法
- 问卷小程序php,问卷调查小程序(tp后台)
- 前端学习路线,如何学习前端
- SQL Server 2014 企业版安装教程
- angularjs1-3,工具方法,bootstrap,多个module,引入jquery
- 华为HCIE这么多的认证方向,哪个方向最有价值,含金量最高?
- 【Linux】进程通信
- 05-现代威胁环境下的10个SIEM用例
- java所定义的版本中不包括_java试题模拟出题
- 为什么寄存器处理数据的速度比内存快?
- 2021泰安高考成绩排名查询,泰安高中学校排名2021最新排名,泰安高中排名前十
- 爬取历史天气数据并绘制成折线图
- 《信号与系统学习笔记》—周期信号的博里叶级数表示(一)
- iOS仿QQ分组效果