C# 客户端网络请求 对HttpClient的封装
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/a1037949156/article/details/90022280
在写C#客户端程序时,或者在服务之间调用API时,我们往往会用到HttpClient来进行交互,这里我做了下简单的二次封装,并不定期更新。
下面是整个封装的HttpClient帮助类:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks; namespace Common
{
/// <summary>
/// Summary: HttpClient公共类
/// Author: Lee Liu
/// Date: 20190114
/// </summary>
public class HttpClientHelper
{
private static HttpClientHelper httpClientHelper = null; private HttpClient httpClient; /// <summary>
/// 构造方法私有,用于单例
/// </summary>
private HttpClientHelper() { } /// <summary>
/// 获取当前类的实例
/// </summary>
/// <returns></returns>
public static HttpClientHelper GetInstance()
{
if (httpClientHelper != null)
{
return httpClientHelper;
}
else
{
HttpClientHelper httpClientHelper = new HttpClientHelper(); //取消使用默认的Cookies
HttpClientHandler handler = new HttpClientHandler() { UseCookies = false };
httpClientHelper.httpClient = new HttpClient(handler);
return httpClientHelper;
}
} /// <summary>
/// Get方法请求
/// </summary>
/// <param name="url">请求地址</param>
/// <returns></returns>
public HttpResponseMessage Get(string url, List<KeyValuePair<string, string>> headers = null)
{
HttpRequestMessage request = new HttpRequestMessage()
{
RequestUri = new Uri(url),
Method = HttpMethod.Get,
};
if (headers != null && headers.Count > )
{
request.Headers.Clear(); foreach (var header in headers)
{
request.Headers.Add(header.Key, header.Value); }
}
HttpResponseMessage response = httpClient.SendAsync(request).Result;
return response;
} /// <summary>
/// Get方法请求
/// </summary>
/// <param name="url">请求地址</param>
/// <returns></returns>
public async Task<HttpResponseMessage> GetAsync(string url, List<KeyValuePair<string, string>> headers = null)
{
HttpRequestMessage request = new HttpRequestMessage()
{
RequestUri = new Uri(url),
Method = HttpMethod.Get,
};
if (headers != null && headers.Count > )
{
request.Headers.Clear();
foreach (var header in headers)
{
request.Headers.Add(header.Key, header.Value);
}
}
return await httpClient.SendAsync(request);
} /// <summary>
/// Post方法请求 application/x-www-form-urlencoded格式
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="paramList">参数集合</param>
/// <returns></returns>
public HttpResponseMessage Post(string url, List<KeyValuePair<String, String>> paramList, List<KeyValuePair<string, string>> headers = null)
{
FormUrlEncodedContent formUrlEncodedContent = new FormUrlEncodedContent(paramList);
if (headers != null && headers.Count > )
{
formUrlEncodedContent.Headers.Clear();
foreach (var header in headers)
{
formUrlEncodedContent.Headers.Add(header.Key, header.Value);
}
}
HttpResponseMessage response = httpClient.PostAsync(new Uri(url), formUrlEncodedContent).Result;
return response;
} public async Task<HttpResponseMessage> PostAsync(string url, List<KeyValuePair<String, String>> paramList, List<KeyValuePair<string, string>> headers = null)
{
FormUrlEncodedContent formUrlEncodedContent = new FormUrlEncodedContent(paramList);
if (headers != null && headers.Count > )
{
formUrlEncodedContent.Headers.Clear();
foreach (var header in headers)
{
formUrlEncodedContent.Headers.Add(header.Key, header.Value);
}
}
return await httpClient.PostAsync(new Uri(url), formUrlEncodedContent);
} /// <summary>
/// Post方法请求 raw data
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="content">raw data</param>
/// <returns></returns>
public HttpResponseMessage Post(string url, string content, List<KeyValuePair<string, string>> headers = null)
{
StringContent stringContent = new StringContent(content, Encoding.UTF8);
if (headers != null && headers.Count > )
{
stringContent.Headers.Clear();
foreach (var header in headers)
{
stringContent.Headers.Add(header.Key, header.Value);
}
} HttpResponseMessage response = httpClient.PostAsync(new Uri(url), stringContent).Result;
return response;
} /// <summary>
/// Post方法请求 raw data
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="content">raw data</param>
/// <returns></returns>
public async Task<HttpResponseMessage> PostAsync(string url, string content, List<KeyValuePair<string, string>> headers = null)
{
StringContent stringContent = new StringContent(content, Encoding.UTF8);
if (headers != null && headers.Count > )
{
stringContent.Headers.Clear();
foreach (var header in headers)
{
stringContent.Headers.Add(header.Key, header.Value);
}
}
return await httpClient.PostAsync(new Uri(url), stringContent); } /// <summary>
/// 释放httpclient
/// </summary>
public void Release()
{
httpClient.Dispose();
} /// <summary>
/// 设置默认请求头
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
public void SetDefaultHeaders(string name, string value)
{
httpClient.DefaultRequestHeaders.Add(name, value);
} /// <summary>
/// 删除默认请求头
/// </summary>
/// <param name="name"></param>
public void RemoveDefaultHeaders(string name)
{
httpClient.DefaultRequestHeaders.Remove(name);
}
}
}
C# 客户端网络请求 对HttpClient的封装的更多相关文章
- Flutter -------- 网络请求之HttpClient
今天来说说Flutter中的网络请求,HttpClient网络请求,包含get,post get var data; _get() async { Map newTitle; var response ...
- React Native中的网络请求fetch和简单封装
React Native中的网络请求fetch使用方法最为简单,但却可以实现大多数的网络请求,需要了解更多的可以访问: https://segmentfault.com/a/1190000003810 ...
- 一劳永逸的解决AFNetworking3.0网络请求问题(面向对象封装大法,block回调)
AFNetworking在iOS网络请求第三方库中占据着半壁江山,前段时间将AFNetworking进行了3.0版本的迁移,运用面向对象的设计将代码进行封装整合,这篇文章主要为还在寻找AFNetwor ...
- swift项目第十天:网络请求工具类的封装
import UIKit /* 必须先导入头文件:import AFNetworking */ import AFNetworking //MARK:-0:定义枚举:以枚举定义请求网络的get和pos ...
- 网络请求框架----HttpClient的get,post和图片上传服务器
HttpClient是Apache Jakarta Common下的子项目,用来提供高效的.最新的.功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议.HttpCli ...
- Android 网络请求库volley的封装,让请求更方便
首先封装一下volley 请求 public class CustomRequest extends StringRequest { private static final String TAG = ...
- 网络请求方法(SDK封装可以替换afn)
//个人觉得 sdk开发时候 最好不要用第三方 最好可以用最原始的方法 替换 此处仅做sdk封装使用 留存+(void)GET:(NSString *)urlStr params:(NSDiction ...
- Android4种网络连接方式HttpClient、HttpURLConnection、OKHttp和Volley优缺点和性能对比
比较的指标: 1.cpu 2.流量 3.电量 4.内存占用 5.联网时间 功能点: 1.重试机制 2.提供的扩展功能 3.易用性 4.是否https 5.是否支持reflect api,OkHttp有 ...
- Android网络请求框架
本篇主要介绍一下Android中经常用到的网络请求框架: 客户端网络请求,就是客户端发起网络请求,经过网络框架的特殊处理,让后将请求发送的服务器,服务器根据 请求的参数,返回客户端需要的数据,经过网络 ...
随机推荐
- BASIS小问题汇总1
try to start SAP system but failed 2019-04-04 Symptom: when i tried to start SAP system, using the c ...
- iOS音频学习笔记二:iOS SDK中与音频有关的相关框架
上层: Media Player Framework: 包含MPMoviePlayerController.MPMoviePlayerViewController.MPMusicPla ...
- 修改mysql/MariaDB数据库的端口号+远程
1.修改端口 2.远程+开放端口 (1)设置远程账号:xxx和密码yyyyyyygrant all privileges on *.* to 'xxx'@'%' identified by 'yyyy ...
- String.getBytes()方法中的中文编码问题
得到一个操作系统默认的编码格式的字节数组.这表示在不同的操作系统下,返回的东西不一样! byte[] a= "中".getBytes() String.getBytes(Strin ...
- Linux系统硬链接和软链接说明 - 运维笔记
在linux系统中有种文件是链接文件,可以用来解决文件的共享使用.链接的方式可以分为两种,一种是硬链接(Hard Link),另一种是软链接或者也称为符号链接(Symbolic Link).先来查看下 ...
- vue+webpack4 脚手架搭建
1, vue 中 h => h(App) 的含义: //render: h => h(App) 是下面内容的缩写: render: function (createElement) { r ...
- ARP详解
1.学习ARP前要了解的内容 建立TCP连接与ARP的关系 应用接受用户提交的数据,触发TCP建立连接,TCP的第一个SYN报文通过connect函数到达IP层,IP层通过查询路由表: 如果目的IP和 ...
- JavaScript 廖
=============== JavaScript代码可以直接嵌在网页的任何地方,不过通常我们都把JavaScript代码放到<head>中 ======注释 // 以双斜杠开头直到行末 ...
- Java位运算总结:位运算用途广泛
前天几天研究了下JDK的Collection接口,本来准备接着研究Map接口,可是一查看HashMap类源码傻眼咯,到处是位运算实现,所以我觉得还是有必要先补补位运算知识,不然代码看起来有点费力.今天 ...
- DOM设置css样式
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...