.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请求

有些APIs要求你使用POST请求。为了实现这个功能,我们改变请求方法和内容类型,然后将请求的数据写入到数据流(stream)中。

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授权请求

del.icio.us API要求你使用授权的请求,使用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());
}  

错误处理

雅虎提供众多基于REST的web服务,不全是使用相同的错误处理方式。有些web服务返回状态码200(表示OK),详细的错误信息在返回来的xml里面,但是有些web服务使用标准的HTTP状态码表示错误信息。请阅读您使用的web服务的文档,了解你所遇到的响应的错误类型。请记住,雅虎基于浏览器授权和HTTP授权是不一样的。调用 HttpRequest.GetResponse() 方法在服务器没有返回状态码200(表示OK),请求超时和网络错误的时候,会引发错误。但是,重定向会自动处理的。
这是一个典型的例子,打印一个网页的内容和基本的HTTP错误代码处理错误。

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服务相关推荐

  1. SOCKET是调用操作系统通信服务的一种机制

    有没有SOCKET,网卡都会接收数据.网卡工作在数据链路层,它只认识链路上邻近的点.它甚至不认识它隔壁的隔壁,它又怎么可能知道传输层的信息呢(起点与终点,是传输层的信息)?...传输层的信息,只能由传 ...

  2. 提交响应后无法调用sendredirect_微服务的那些事(三),微服务的远程调用方式。RPC和HTTP...

    2.远程调用方式 无论是微服务还是SOA,都面临着服务间的远程调用.那么服务间的远程调用方式有哪些呢? 常见的远程调用方式有以下几种: RPC:Remote Produce Call远程过程调用,类似 ...

  3. 实现远程调用_微服务的那些事(三),微服务的远程调用方式。RPC和HTTP

    2.远程调用方式 无论是微服务还是SOA,都面临着服务间的远程调用.那么服务间的远程调用方式有哪些呢? 常见的远程调用方式有以下几种: RPC:Remote Produce Call远程过程调用,类似 ...

  4. JAVA与.NET的相互调用——通过Web服务实现相互调用

    JAVA与.NET是现今世界竞争激烈的两大开发媒体,两者语言有很多相似的地方.而在很多大型的开发项目里面,往往需要使用两种语言进行集成开发.而很多的开发人员都会偏向于其中一种语言,在使用集成开发的时候 ...

  5. 【spring boot】使用RestTemplate调用百度坐标转换服务

    前言 spring boot 2.0.0.RELEASE http://api.map.baidu.com/geoconv/v1/?coords=114.21892734521,29.57542977 ...

  6. 小程序微信授权登录服务器异常,解决调试腾讯云微信小程序Demo错误“登录失败:调用鉴权服务失败#40029_WEIXIN_CODE_ERR”...

    此文章解决大家有可能遇到的"登录失败:调用鉴权服务失败#40029的问题"~~ 很多人出现上面的问题,那是因为:如果在购买解决方案时,把AppId 和 AppSecret 填写错误 ...

  7. feign调用多个服务_Spring Cloud 快速入门系列之feign–微服务之间的调用

    我们将一个大的应用拆成多个小的服务之后,紧接着的一个问题就是,原本都在一个项目里,方法我可以随便调用,但是拆开后,原来的方法就没法直接调用了,这时候要怎么办? Spring Cloud提供了feign ...

  8. js调用python接口_JavaScript如何调用Python后端服务

    欢迎关注[无量测试之道]公众号,回复[领取资源], Python编程学习资源干货. Python+Appium框架APP的UI自动化. Python+Selenium框架Web的UI自动化. Pyth ...

  9. SpringCloud 入门教程(六): 用声明式REST客户端Feign调用远端HTTP服务

    首先简单解释一下什么是声明式实现? 要做一件事, 需要知道三个要素,where, what, how.即在哪里( where)用什么办法(how)做什么(what).什么时候做(when)我们纳入ho ...

最新文章

  1. .net简单算法实现无限级分类(一)
  2. APP的CPU,内存,耗电,流量测试工具
  3. 2021年度 Egon Balas 奖得主:达摩院印卧涛
  4. 浅谈(Java)AIO-异步IO
  5. 编程器测试软件,CH341A编程器
  6. 【转】自动化专业十大看家课程
  7. linux中#和## 用法
  8. 问卷小程序php,问卷调查小程序(tp后台)
  9. 前端学习路线,如何学习前端
  10. SQL Server 2014 企业版安装教程
  11. angularjs1-3,工具方法,bootstrap,多个module,引入jquery
  12. 华为HCIE这么多的认证方向,哪个方向最有价值,含金量最高?
  13. 【Linux】进程通信
  14. 05-现代威胁环境下的10个SIEM用例
  15. java所定义的版本中不包括_java试题模拟出题
  16. 为什么寄存器处理数据的速度比内存快?
  17. 2021泰安高考成绩排名查询,泰安高中学校排名2021最新排名,泰安高中排名前十
  18. 爬取历史天气数据并绘制成折线图
  19. 《信号与系统学习笔记》—周期信号的博里叶级数表示(一)
  20. iOS仿QQ分组效果

热门文章

  1. 显著性检测—谱残差方法分析与实现
  2. 小程序直播间点赞向上随机飘动画
  3. July, 29(R)
  4. php 获取a-z中随机_PHP中的随机性-您感到幸运吗?
  5. Android:代码混淆反混淆
  6. Spark特征处理之RFormula源码解析
  7. 通过旋转候选框实现任意方向的场景文本检测
  8. Oracle数据库 登录命令 用户管理 建表 修改字段 数据类型 约束 增删改查
  9. Pandas - Review
  10. wro4j和maven plugin在编译期间压缩静态资源.