当前位置: 首页 > news >正文

.NET HttpWebRequest、WebClient、HttpClient

HttpWebRequest:
继承 WebRequest
命名空间: System.Net,这是.NET创建者最初开发用于使用HTTP请求的标准类。使用HttpWebRequest可以让开发者控制请求/响应流程的各个方面,如 timeouts, cookies, headers, protocols。另一个好处是HttpWebRequest类不会阻塞UI线程。例如,当您从响应很慢的API服务器下载大文件时,您的应用程序的UI不会停止响应。HttpWebRequest通常和WebResponse一起使用,一个发送请求,一个获取数据。HttpWebRquest更为底层一些,能够对整个访问过程有个直观的认识,但同时也更加复杂一些。
 //POST方法
public static string HttpPost(string Url, string postDataStr)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = “POST”;
request.ContentType = “application/x-www-form-urlencoded”;
Encoding encoding = Encoding.UTF8;
byte[] postData = encoding.GetBytes(postDataStr);
request.ContentLength = postData.Length;
Stream myRequestStream = request.GetRequestStream();
myRequestStream.Write(postData, 0, postData.Length);
myRequestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, encoding);
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();

return retString;
}
//GET方法
public static string HttpGet(string Url, string postDataStr)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == “” ? “” : “?”) + postDataStr);
request.Method = “GET”;
request.ContentType = “text/html;charset=UTF-8”;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding(“utf-8”));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}

WebClient:
public abstract class WebRequest : MarshalByRefObject, ISerializable
public class HttpWebRequest : WebRequest, ISerializable
public class WebClient : Component
命名空间System.Net,WebClient是一种更高级别的抽象,是HttpWebRequest为了简化最常见任务而创建的,使用过程中你会发现他缺少基本的header,timeoust的设置,不过这些可以通过继承httpwebrequest来实现。相对来说,WebClient比WebRequest更加简单,它相当于封装了request和response方法,不过需要说明的是,**Webclient和WebRequest继承的是不同类,两者在继承上没有任何关系。**使用WebClient可能比HttpWebRequest直接使用更慢(大约几毫秒),但却更为简单,减少了很多细节,代码量也比较少。
public class WebClientHelper
{
public static string DownloadString(string url)
{
WebClient wc = new WebClient();
//wc.BaseAddress = url; //设置根目录
wc.Encoding = Encoding.UTF8; //设置按照何种编码访问,如果不加此行,获取到的字符串中文将是乱码
string str = wc.DownloadString(url);
return str;
}
public static string DownloadStreamString(string url)
{
WebClient wc = new WebClient();
wc.Headers.Add(“User-Agent”, “Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36”);
Stream objStream = wc.OpenRead(url);
StreamReader _read = new StreamReader(objStream, Encoding.UTF8); //新建一个读取流,用指定的编码读取,此处是utf-8
string str = _read.ReadToEnd();
objStream.Close();
_read.Close();
return str;
}

public static void DownloadFile(string url, string filename)
{
  WebClient wc = new WebClient();
  wc.DownloadFile(url, filename);   //下载文件
}

public static void DownloadData(string url, string filename)
{
  WebClient wc = new WebClient();
  byte [] bytes = wc.DownloadData(url);  //下载到字节数组
  FileStream fs = new FileStream(filename, FileMode.Create);
  fs.Write(bytes, 0, bytes.Length); 
  fs.Flush();
  fs.Close();
}

public static void DownloadFileAsync(string url, string filename)
{
  WebClient wc = new WebClient();
  wc.DownloadFileCompleted += DownCompletedEventHandler;
  wc.DownloadFileAsync(new Uri(url), filename);
  Console.WriteLine("下载中。。。");
}
private static void DownCompletedEventHandler(object sender, AsyncCompletedEventArgs e)
{
  Console.WriteLine(sender.ToString());  //触发事件的对象
  Console.WriteLine(e.UserState);
  Console.WriteLine(e.Cancelled);
  Console.WriteLine("异步下载完成!");
}

public static void DownloadFileAsync2(string url, string filename)
{
  WebClient wc = new WebClient();
  wc.DownloadFileCompleted += (sender, e) =>
  {
    Console.WriteLine("下载完成!");
    Console.WriteLine(sender.ToString());
    Console.WriteLine(e.UserState);
    Console.WriteLine(e.Cancelled);
  };
  wc.DownloadFileAsync(new Uri(url), filename);
  Console.WriteLine("下载中。。。");
}

}
HttpClient:
public class HttpClient : HttpMessageInvoker
HttpClient是.NET4.5引入的一个HTTP客户端库,其命名空间为 System.Net.Http ,.NET 4.5之前我们可能使用WebClient和HttpWebRequest来达到相同目的。HttpClient利用了最新的面向任务模式,使得处理异步请求非常容易。它适合用于多次请求操作,一般设置好默认头部后,可以进行重复多次的请求,基本上用一个实例可以提交任何的HTTP请求。HttpClient有预热机制,第一次进行访问时比较慢,所以不应该用到HttpClient就new一个出来,应该使用单例或其他方式获取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 = 23 };
        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的实例
在这里插入图片描述

相关文章:

  • elementPlus 的el-select二次封装
  • mysql 8版本windows安装
  • 关于BLE5.3蓝牙串口透传芯片CH9142
  • 2022年的 自己
  • Unity UI Toolkit学习笔记-Runtime UI 案例实践
  • 成都聚华祥:抖音账户应该怎么做?
  • 基于elementPlus的el-upload的二次封装组件
  • 肾囊肿有哪些异常症状表现?
  • 适合学生用的蓝牙耳机哪款好?学生党无线蓝牙耳机推荐
  • 如何在linux系统上部署皕杰报表
  • 万魔和南卡蓝牙耳机哪款比较好用?万魔和南卡A2蓝牙耳机对比测评
  • 收藏:不能不刷的数字后端面试题,含解析
  • uniapp 小程序单页面设置横屏
  • 【Spring Cloud】新闻头条微服务项目:引入ElasticSearch建立文章搜索索引
  • 深度学习之文本分类 ----FastText
  • __proto__ 和 prototype的关系
  • “大数据应用场景”之隔壁老王(连载四)
  • Angularjs之国际化
  • Git的一些常用操作
  • input的行数自动增减
  • JavaScript类型识别
  • JavaScript中的对象个人分享
  • KMP算法及优化
  • magento2项目上线注意事项
  • MD5加密原理解析及OC版原理实现
  • MYSQL 的 IF 函数
  • mysql外键的使用
  • unity如何实现一个固定宽度的orthagraphic相机
  • VuePress 静态网站生成
  • vue的全局变量和全局拦截请求器
  • 安装python包到指定虚拟环境
  • 工作踩坑系列——https访问遇到“已阻止载入混合活动内容”
  • 回顾2016
  • 前端知识点整理(待续)
  • 浅析微信支付:申请退款、退款回调接口、查询退款
  • Java性能优化之JVM GC(垃圾回收机制)
  • Spark2.4.0源码分析之WorldCount 默认shuffling并行度为200(九) ...
  • ​软考-高级-信息系统项目管理师教程 第四版【第23章-组织通用管理-思维导图】​
  • (C#)Windows Shell 外壳编程系列4 - 上下文菜单(iContextMenu)(二)嵌入菜单和执行命令...
  • (Demo分享)利用原生JavaScript-随机数-实现做一个烟花案例
  • (Matalb时序预测)WOA-BP鲸鱼算法优化BP神经网络的多维时序回归预测
  • (ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY)讲解
  • (ZT) 理解系统底层的概念是多么重要(by趋势科技邹飞)
  • (分类)KNN算法- 参数调优
  • (免费领源码)python#django#mysql公交线路查询系统85021- 计算机毕业设计项目选题推荐
  • (七)理解angular中的module和injector,即依赖注入
  • (全部习题答案)研究生英语读写教程基础级教师用书PDF|| 研究生英语读写教程提高级教师用书PDF
  • (四)汇编语言——简单程序
  • (学习日记)2024.03.25:UCOSIII第二十二节:系统启动流程详解
  • .\OBJ\test1.axf: Error: L6230W: Ignoring --entry command. Cannot find argumen 'Reset_Handler'
  • .NET Core 2.1路线图
  • .NET core 自定义过滤器 Filter 实现webapi RestFul 统一接口数据返回格式
  • .NET企业级应用架构设计系列之技术选型
  • /ThinkPHP/Library/Think/Storage/Driver/File.class.php  LINE: 48
  • @data注解_一枚 架构师 也不会用的Lombok注解,相见恨晚