WebRequest/HttpWebRequest/HttpRequest/WebClient/HttpClient的区别
1.WebRequest和HttpWebRequest
WebRequest 的命名空间是: System.Net ,它是HttpWebRequest的抽象父类(还有其他子类如FileWebRequest ,FtpWebRequest),WebRequest的子类都用于从web获取资源。HttpWebRequest利用HTTP 协议和服务器交互,通常是通过 GET 和 POST 两种方式来对数据进行获取和提交
一个栗子:
static void Main(string[] args)
{
// 创建一个WebRequest实例(默认get方式)
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.baidu.com");
//可以指定请求的类型
//request.Method = "POST";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(response.StatusDescription);
// 接收数据
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
// 关闭stream和response
reader.Close();
dataStream.Close();
response.Close();
}
运行后输出百度网页的html字符串,如下:

2.HttpRequest
- HttpRequest类的命名空间是:System.Web,它是一个密封类,其作用是让服务端读取客户端发送的请求,我们最熟悉的HttpRequest的实例应该是WebForm中Page类的属性Request了,我们可以轻松地从Request属性的QueryString,Form,Cookies集合获取数据中,也可以通过Request["Key"]获取自定义数据,一个栗子:
protected void Page_Load(object sender, EventArgs e)
{
//从Request中获取商品Id
string rawId = Request["ProductID"];
int productId;
if (!String.IsNullOrEmpty(rawId) && int.TryParse(rawId, out productId))
{
//把商品放入购物车
using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
{
usersShoppingCart.AddToCart(productId);
}
}
else
{
throw new Exception("Tried to call AddToCart.aspx without setting a ProductId.");
}
//跳转到购物车页面
Response.Redirect("ShoppingCart.aspx");
}
3.WebClient
命名空间是System.Net,WebClient很轻量级的访问Internet资源的类,在指定uri后可以发送和接受数据。WebClient提供了 DownLoadData,DownLoadFile,UploadData,UploadFile 方法,同时通过了这些方法对应的异步方法,通过WebClient我们可以很方便地上传和下载文件。
简单使用:
static void Main(string[] args)
{
WebClient wc = new WebClient();
wc.BaseAddress = "http://www.baidu.com/"; //设置根目录
wc.Encoding = Encoding.UTF8; //设置按照何种编码访问,如果不加此行,获取到的字符串中文将是乱码
string str = wc.DownloadString("/"); //字符串形式返回资源
Console.WriteLine(str); //----------------------以下为OpenRead()以流的方式读取----------------------
wc.Headers.Add("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
wc.Headers.Add("Accept-Language", "zh-cn");
wc.Headers.Add("UA-CPU", "x86");
//wc.Headers.Add("Accept-Encoding","gzip, deflate"); //因为我们的程序无法进行gzip解码所以如果这样请求获得的资源可能无法解码。当然我们可以给程序加入gzip处理的模块 那是题外话了。
wc.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
//Headers 用于添加添加请求的头信息
Stream objStream = wc.OpenRead("?tn=98050039_dg&ch=1"); //获取访问流
StreamReader _read = new StreamReader(objStream, Encoding.UTF8); //新建一个读取流,用指定的编码读取,此处是utf-8
Console.Write(_read.ReadToEnd()); //输出读取到的字符串 //------------------------DownloadFile下载文件-------------------------------
wc.DownloadFile("http://www.baidu.com/img/shouye_b5486898c692066bd2cbaeda86d74448.jpg", @"D:\123.jpg"); //将远程文件保存到本地 //------------------------DownloadFile下载到字节数组-------------------------------
byte[] bytes = wc.DownloadData("http://www.baidu.com/img/shouye_b5486898c692066bd2cbaeda86d74448.gif");
FileStream fs = new FileStream(@"E:\123.gif", FileMode.Create);
fs.Write(bytes, , bytes.Length); fs.Flush();
WebHeaderCollection whc = wc.ResponseHeaders;
//获取响应头信息
foreach (string s in whc) {
Console.WriteLine(s + ":" + whc.Get(s));
}
Console.ReadKey();
}
一个使用WebClient下载文件的栗子:
static void Main(string[] args)
{ WebClient wc = new WebClient(); //直接下载
Console.WriteLine("直接下载开始。。。");
wc.DownloadFile("http://www.kykan.cn/d/file/djgz/20170506/8e207019d3a8e6114bfc7f50710211c1.xlsx", @"D:\ku.xlsx");
Console.WriteLine("直接下载完成!!!"); //下载完成后输出 下载完成了吗? //异步下载
wc.DownloadFileAsync(new Uri("http://www.kykan.cn/d/file/djgz/20170506/8e207019d3a8e6114bfc7f50710211c1.xlsx"), @"D:\ku.xlsx");
wc.DownloadFileCompleted += DownCompletedEventHandler;
Console.WriteLine("do something else...");
Console.ReadKey();
} public static void DownCompletedEventHandler(object sender, AsyncCompletedEventArgs e)
{
Console.WriteLine("异步下载完成!");
}
4.HttpClient
HttpClient是.NET4.5引入的一个HTTP客户端库,其命名空间为 System.Net.Http 。.NET 4.5之前我们可能使用WebClient和HttpWebRequest来达到相同目的。HttpClient利用了最新的面向任务模式,使得处理异步请求非常容易。
下边是一个使用控制台程序异步请求接口的栗子:
static void Main(string[] args)
{
const string GetUrl = "http://xxxxxxx/api/UserInfo/GetUserInfos";//查询用户列表的接口,Get方式访问
const string PostUrl = "http://xxxxxxx/api/UserInfo/AddUserInfo";//添加用户的接口,Post方式访问 //使用Get请求
GetFunc(GetUrl); UserInfo user = new UserInfo { Name = "jack", Age = };
string userStr = JsonHelper.SerializeObject(user);//序列化
//使用Post请求
PostFunc(PostUrl, userStr);
Console.ReadLine();
} /// <summary>
/// Get请求
/// </summary>
/// <param name="path"></param>
static async void GetFunc(string path)
{
//消息处理程序
HttpClientHandler handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
HttpClient httpClient = new HttpClient();
//异步get请求
HttpResponseMessage response = await httpClient.GetAsync(path);
//确保响应正常,如果响应不正常EnsureSuccessStatusCode()方法会抛出异常
response.EnsureSuccessStatusCode();
//异步读取数据,格式为String
string resultStr = await response.Content.ReadAsStringAsync();
Console.WriteLine(resultStr);
} /// <summary>
/// Post请求
/// </summary>
/// <param name="path"></param>
/// <param name="data"></param>
static async void PostFunc(string path, string data)
{
HttpClientHandler handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
HttpClient httpClient = new HttpClient(handler);
//HttpContent是HTTP实体正文和内容标头的基类。
HttpContent httpContent = new StringContent(data, Encoding.UTF8, "text/json");
//httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("BasicAuth", Ticket);//验证请求头赋值
//httpContent.Headers.Add(string name,string value) //添加自定义请求头 //发送异步Post请求
HttpResponseMessage response = await httpClient.PostAsync(path, httpContent);
response.EnsureSuccessStatusCode();
string resultStr = await response.Content.ReadAsStringAsync();
Console.WriteLine(resultStr);
}
}
注意:因为HttpClient有预热机制,第一次进行访问时比较慢,所以我们最好不要用到HttpClient就new一个出来,应该使用单例或其他方式获取HttpClient的实例。上边的栗子为了演示方便直接new的HttpClient实例。
HttpClient还有很多其他功能,如附带Cookie,请求拦截等,可以参考https://www.cnblogs.com/wywnet/p/httpclient.html
参考文章:
1.https://www.cnblogs.com/wywnet/p/httpclient.html
2.https://www.cnblogs.com/kissdodog/archive/2013/02/19/2917004.html
WebRequest/HttpWebRequest/HttpRequest/WebClient/HttpClient的区别的更多相关文章
- HttpRequest,WebRequest,HttpWebRequest,WebClient,HttpClient 之间的区别
HttpRequest,WebRequest,HttpWebRequest,WebClient,HttpClient 今天我们来聊一下他们之间的关系与区别. HttpRequest 类 .NET Fr ...
- WebClient, HttpClient, HttpWebRequest ,RestSharp之间的区别与抉择
NETCore提供了三种不同类型用于生产的REST API: HttpWebRequest;WebClient;HttpClient,开源社区创建了另一个名为RestSharp的库.如此多的http库 ...
- HttpWebRequest和WebClient的区别
HttpWebRequest和WebClient的区别(From Linzheng): 1,HttpWebRequest是个抽象类,所以无法new的,需要调用HttpWebRequest.Creat ...
- HttpWebRequest 改为 HttpClient 踩坑记-请求头设置
HttpWebRequest 改为 HttpClient 踩坑记-请求头设置 Intro 这两天改了一个项目,原来的项目是.net framework 项目,里面处理 HTTP 请求使用的是 WebR ...
- Linux中用HttpWebRequest或WebClient访问远程https路径
要想在Linux中用HttpWebRequest或WebClient访问远程https路径,需要作如下处理: 1,更新linux根证书(只需一次,在安装mono或安装jexus独立版后执行) sudo ...
- webrequest、httpwebrequest、webclient、HttpClient 四个类的区别
一.在 framework 开发环境下: webrequest.httpwebreques 都是基于Windows Api 进行包装, webclient 是基于webrequest 进行包装:(经 ...
- webrequest HttpWebRequest webclient/HttpClient
webrequest(abstract类,不可直接用) <--- (继承)---- HttpWebRequest(更好的控制请求) <--- (继承)---- webclient (简单快 ...
- .net学习笔记----HttpRequest,WebRequest,HttpWebRequest区别
WebRequest是一个虚类/基类,HttpWebRequest是WebRequest的具体实现 HttpRequest类的对象用于服务器端,获取客户端传来的请求的信息,包括HTTP报文传送过来的所 ...
- HttpWebRequest、WebClient、RestSharp、HttpClient区别和用途
HttpWebRequest 已经不推荐直接使用了,这已经作为底层机制,不适合业务代码使用,比如写爬虫的时候WebClient 不想为http细节处理而头疼的coder而生,由于内部已经处理了通用设置 ...
随机推荐
- UESTC482-Charitable Exchange-bfs优先队列
#include <cstring> #include <algorithm> #include <iostream> #include <queue> ...
- Django ContentType组件
ContentType组件 引入 现在我们有这样一个需求~我们的商城里有很多的商品~~节日要来了~我们要搞活动~~ 那么我们就要设计优惠券~~优惠券都有什么类型呢~~满减的~折扣的~立减的~~ 我们对 ...
- python基础成长之路三
1,基础数据类型 总览 int :数字 用于计数,计算,运算等...1 , 2 , 3 , 100 , ... str :字符串 用户少量的数据储存,便于操作 "这就是字符串&qu ...
- P1319 压缩技术
很多小伙伴卡在此题的原因可能是因为不知道怎么让它输入无限个数字吧?除了用string,在这里我是看到“压缩码保证 N * N=交替的各位数之和”这一句话,想到用while循环.只要输入的数的总和t小于 ...
- Spring03-AOP
一. AOP介绍 1. Aop介绍 AOP(Aspect Oriented Programming),即面向切面编程,可以说是OOP(Object Oriented Programming,面向对象编 ...
- Spring02-注入和注解方式操作
一. 依赖注入 测试类:Person.java 创建配置文件:applicationContext-injection.xml 创建测试代码:InjectionTest.java 1. set方法注入 ...
- C# 获取变量或对象的栈与堆地址
C# 获取变量或对象的栈与堆地址 来源 https://www.cnblogs.com/xiaoyaodijun/p/6605070.html using System; using System.C ...
- vscode跳转到函数定义处
需要安装对应语言的插件,帮助-欢迎使用,安装javascript, php php还需要安装php7, 到官网https://windows.php.net/download#php-7.2 下载解压 ...
- 【刷题】BZOJ 2759 一个动态树好题
Description 有N个未知数x[1..n]和N个等式组成的同余方程组: x[i]=k[i]*x[p[i]]+b[i] mod 10007 其中,k[i],b[i],x[i]∈[0,10007) ...
- Hdoj 1421.搬寝室 题解
Problem Description 搬寝室是很累的,xhd深有体会.时间追述2006年7月9号,那天xhd迫于无奈要从27号楼搬到3号楼,因为10号要封楼了.看着寝室里的n件物品,xhd开始发呆, ...