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

3.https://docs.microsoft.com/en-us/dotnet/api/system.net.httpwebrequest?redirectedfrom=MSDN&view=netframework-4.7.2

WebRequest/HttpWebRequest/HttpRequest/WebClient/HttpClient的区别的更多相关文章

  1. HttpRequest,WebRequest,HttpWebRequest,WebClient,HttpClient 之间的区别

    HttpRequest,WebRequest,HttpWebRequest,WebClient,HttpClient 今天我们来聊一下他们之间的关系与区别. HttpRequest 类 .NET Fr ...

  2. WebClient, HttpClient, HttpWebRequest ,RestSharp之间的区别与抉择

    NETCore提供了三种不同类型用于生产的REST API: HttpWebRequest;WebClient;HttpClient,开源社区创建了另一个名为RestSharp的库.如此多的http库 ...

  3. HttpWebRequest和WebClient的区别

     HttpWebRequest和WebClient的区别(From Linzheng): 1,HttpWebRequest是个抽象类,所以无法new的,需要调用HttpWebRequest.Creat ...

  4. HttpWebRequest 改为 HttpClient 踩坑记-请求头设置

    HttpWebRequest 改为 HttpClient 踩坑记-请求头设置 Intro 这两天改了一个项目,原来的项目是.net framework 项目,里面处理 HTTP 请求使用的是 WebR ...

  5. Linux中用HttpWebRequest或WebClient访问远程https路径

    要想在Linux中用HttpWebRequest或WebClient访问远程https路径,需要作如下处理: 1,更新linux根证书(只需一次,在安装mono或安装jexus独立版后执行) sudo ...

  6. webrequest、httpwebrequest、webclient、HttpClient 四个类的区别

    一.在 framework 开发环境下: webrequest.httpwebreques  都是基于Windows Api 进行包装, webclient 是基于webrequest 进行包装:(经 ...

  7. webrequest HttpWebRequest webclient/HttpClient

    webrequest(abstract类,不可直接用) <--- (继承)---- HttpWebRequest(更好的控制请求) <--- (继承)---- webclient (简单快 ...

  8. .net学习笔记----HttpRequest,WebRequest,HttpWebRequest区别

    WebRequest是一个虚类/基类,HttpWebRequest是WebRequest的具体实现 HttpRequest类的对象用于服务器端,获取客户端传来的请求的信息,包括HTTP报文传送过来的所 ...

  9. HttpWebRequest、WebClient、RestSharp、HttpClient区别和用途

    HttpWebRequest 已经不推荐直接使用了,这已经作为底层机制,不适合业务代码使用,比如写爬虫的时候WebClient 不想为http细节处理而头疼的coder而生,由于内部已经处理了通用设置 ...

随机推荐

  1. Redis 5种数据结构

    转载:https://baijiahao.baidu.com/s?id=1593806211408070879&wfr=spider&for=pc Redis数据类型 Redis支持五 ...

  2. 大学jsp实验4include,forword

    一.实验目的与要求 1.掌握常用JSP动作标记的使用. 二.实验内容 1.include动作标记的使用 编写一个名为shiyan4_1.jsp的JSP页面,页面内容自定,但要求使用include动作标 ...

  3. 【XSY2751】Mythological IV 线性插值

    题目描述 已知\(f(x)\)为\(k\)次多项式. 给你\(f(0),f(1),\ldots,f(k)\),求 \[ \sum_{i=1}^nf(i)q^i \] \(k\leq 500000,n\ ...

  4. 【XSY1294】sub 树链剖分

    题目描述 给你一棵\(n\)个点的无根树,节点\(i\)有权值\(v_i\).现在有\(m\)次操作,操作有如下两种: \(1~x~y\):把\(v_x\)改成\(y\). \(2\):选择一个连通块 ...

  5. 运行os.fork()报AttributeError: module 'os' has no attribute 'fork'

    现象 报错代码 def handle(s, c, db): pid = os.fork() if pid == 0: s.close() do_child(c, db) sys.exit() else ...

  6. 数字平滑 前端插件JS&CSS库

    CDN DEMO 拷贝可用: <!DOCTYPE html> <link rel="stylesheet" href="https://cdn.boot ...

  7. 「2017 Multi-University Training Contest 8」2017多校训练8

    1009 I am your Father! (最小树形图-朱刘算法) 题目链接 HDU6141 I am your Father! 求有向图最大生成树,要求n的父节点尽量小. 我们将所有wi变为-w ...

  8. centos7下安装vnc更改vnc默认端口号

    应用场景:某些情景下,需要用的linux的桌面环境,Ubuntu的桌面性能在linux发行版中算是数一数二的,如果不熟悉Debian系统,Centos/RHEL系列也行:   我这里的场景是开发人员不 ...

  9. Java collection 容器

    http://www.codeceo.com/article/java-container-brief-introduction.html Java实用类库提供了一套相当完整的容器来帮助我们解决很多具 ...

  10. 【CF242E】Xor Segment

    题目大意:给定一个长度为 N 的序列,支持两种询问,即:区间异或,区间求和. 题解:加深了对线段树的理解. 对于线段树维护的变量一定是易于 modify 的,对于查询的答案只需用维护的东西进行组合而成 ...