HttpWebRequest HttpClient
HttpWebRequest HttpClient 简单封装使用,支持https
HttpWebRequest
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using TT.Utilities.Extends; namespace TT.Utilities.Web
{
public class HttpRequest
{
public static HttpWebRequest CreateHttpWebRequest(string url)
{
HttpWebRequest request;
//如果是发送HTTPS请求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
//ServicePointManager.DefaultConnectionLimit = 1000;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version11;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Proxy = null;
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
return request;
} /// <summary>
///
/// </summary>
/// <param name="url">url</param>
/// <param name="dic">参数</param>
/// <param name="headerDic">请求头参数</param>
/// <returns></returns>
public static string DoPost(string url, Dictionary<string, string> dic, Dictionary<string, string> headerDic)
{
HttpWebRequest request = CreateHttpWebRequest(url);
request.Method = "POST";
request.Accept = "*/*";
request.ContentType = HttpContentTypes.GetContentType(HttpContentTypes.HttpContentTypeEnum.JSON);
if (headerDic != null && headerDic.Count > )
{
foreach (var item in headerDic)
{
request.Headers.Add(item.Key, item.Value);
}
}
if (dic != null && dic.Count > )
{
var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(dic);
byte[] buffer = Encoding.UTF8.GetBytes(jsonStr);
request.ContentLength = buffer.Length;
try
{
request.GetRequestStream().Write(buffer, , buffer.Length);
}
catch (WebException ex)
{
throw ex;
}
}
else
{
request.ContentLength = ;
}
return HttpResponse(request);
} public static string DoPost(string url, Dictionary<string, string> dic)
{
return DoPost(url, dic, null);
} static object olock = new object();
public static string HttpResponse(HttpWebRequest request)
{
try
{
//lock (olock)
//{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
var contentEncodeing = response.ContentEncoding.ToLower(); if (!contentEncodeing.Contains("gzip") && !contentEncodeing.Contains("deflate"))
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
else
{
#region gzip,deflate 压缩解压
if (contentEncodeing.Contains("gzip"))
{
using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
{
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
else //if (contentEncodeing.Contains("deflate"))
{
using (DeflateStream stream = new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress))
{
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
#endregion gzip,deflate 压缩解压
}
}
//}
}
catch (WebException ex)
{
throw ex;
}
} public static string DoGet(string url, Dictionary<string, string> dic)
{
try
{
var argStr = dic == null ? "" : dic.ToSortUrlParamString();
argStr = string.IsNullOrEmpty(argStr) ? "" : ("?" + argStr);
HttpWebRequest request = CreateHttpWebRequest(url + argStr);
request.Method = "GET";
request.ContentType = "application/json";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
throw ex;
}
} public static string DoGet(string url, Dictionary<string, string> dic, Dictionary<string, string> headerDic)
{
try
{
var argStr = dic == null ? "" : dic.ToSortUrlParamString();
argStr = string.IsNullOrEmpty(argStr) ? "" : ("?" + argStr);
HttpWebRequest request = CreateHttpWebRequest(url + argStr);
request.Method = "GET";
request.ContentType = "application/json";
foreach (var item in headerDic)
{
request.Headers.Add(item.Key, item.Value);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
throw ex;
}
} private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
}
}
}
加入request timeout
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using TT.Utilities.Extends; namespace TT.Utilities.Web
{
public class HttpRequest
{
public static HttpWebRequest CreateHttpWebRequest(string url, int timeoutSecond = )
{
HttpWebRequest request;
//如果是发送HTTPS请求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
//ServicePointManager.DefaultConnectionLimit = 1000;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version11;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Proxy = null;
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
request.Timeout = timeoutSecond * 1000;
return request;
} /// <summary>
///
/// </summary>
/// <param name="url">url</param>
/// <param name="dic">参数</param>
/// <param name="headerDic">请求头参数</param>
/// <returns></returns>
public static string DoPost(string url, Dictionary<string, string> dic, Dictionary<string, string> headerDic, int timeoutSecond = )
{
HttpWebRequest request = CreateHttpWebRequest(url, timeoutSecond);
request.Method = "POST";
request.Accept = "*/*";
request.ContentType = HttpContentTypes.GetContentType(HttpContentTypes.HttpContentTypeEnum.JSON);
if (headerDic != null && headerDic.Count > )
{
foreach (var item in headerDic)
{
request.Headers.Add(item.Key, item.Value);
}
}
if (dic != null && dic.Count > )
{
var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(dic);
byte[] buffer = Encoding.UTF8.GetBytes(jsonStr);
request.ContentLength = buffer.Length;
try
{
request.GetRequestStream().Write(buffer, , buffer.Length);
}
catch (WebException ex)
{
throw ex;
}
}
else
{
request.ContentLength = ;
}
return HttpResponse(request);
} public static string DoPost(string url, Dictionary<string, string> dic, int timeoutSecond = )
{
return DoPost(url, dic, null, timeoutSecond);
} static object olock = new object();
public static string HttpResponse(HttpWebRequest request)
{
try
{
//lock (olock)
//{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
var contentEncodeing = response.ContentEncoding.ToLower(); if (!contentEncodeing.Contains("gzip") && !contentEncodeing.Contains("deflate"))
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
else
{
#region gzip,deflate 压缩解压
if (contentEncodeing.Contains("gzip"))
{
using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
{
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
else //if (contentEncodeing.Contains("deflate"))
{
using (DeflateStream stream = new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress))
{
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
#endregion gzip,deflate 压缩解压
}
}
//}
}
catch (WebException ex)
{
throw ex;
}
} public static string DoGet(string url, Dictionary<string, string> dic, int timeoutSecond = )
{
try
{
var argStr = dic == null ? "" : dic.ToSortUrlParamString();
argStr = string.IsNullOrEmpty(argStr) ? "" : ("?" + argStr);
HttpWebRequest request = CreateHttpWebRequest(url + argStr, timeoutSecond);
request.Method = "GET";
request.ContentType = "application/json";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
throw ex;
}
} public static string DoGet(string url, Dictionary<string, string> dic, Dictionary<string, string> headerDic, int timeoutSecond = )
{
try
{
var argStr = dic == null ? "" : dic.ToSortUrlParamString();
argStr = string.IsNullOrEmpty(argStr) ? "" : ("?" + argStr);
HttpWebRequest request = CreateHttpWebRequest(url + argStr, timeoutSecond);
request.Method = "GET";
request.ContentType = "application/json";
foreach (var item in headerDic)
{
request.Headers.Add(item.Key, item.Value);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
throw ex;
}
} private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
}
}
}
HttpClient
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using TT.Utilities.Extends;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates; namespace TT.Utilities.Web
{
public class HttpClientUti
{
/// <summary>
/// post 提交json格式参数
/// </summary>
/// <param name="url">url</param>
/// <param name="postJson">json字符串</param>
/// <returns></returns>
public static string DoPost(string url, string postJson)
{
HttpContent content = new StringContent(postJson);
content.Headers.ContentType = new MediaTypeHeaderValue(HttpContentTypes.GetContentType(HttpContentTypes.HttpContentTypeEnum.JSON));
return DoPost(url, content);
} /// <summary>
/// post 提交json格式参数
/// </summary>
/// <param name="url">url</param>
/// <param name="argDic">参数字典</param>
/// <param name="headerDic">请求头字典</param>
/// <returns></returns>
public static string DoPost(string url, Dictionary<string, string> argDic, Dictionary<string, string> headerDic)
{
argDic.ToSortUrlParamString();
var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(argDic);
HttpContent content = new StringContent(jsonStr);
content.Headers.ContentType = new MediaTypeHeaderValue(HttpContentTypes.GetContentType(HttpContentTypes.HttpContentTypeEnum.JSON));
if (headerDic != null)
{
foreach (var item in headerDic)
{
content.Headers.Add(item.Key, item.Value);
}
}
return DoPost(url, content);
} /// <summary>
/// HttpClient POST 提交
/// </summary>
/// <param name="url">url</param>
/// <param name="content">HttpContent</param>
/// <returns></returns>
public static string DoPost(string url, HttpContent content)
{
try
{
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
using (var http = new HttpClient(handler))
{
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
} var response = http.PostAsync(url, content).Result;
//确保HTTP成功状态值
response.EnsureSuccessStatusCode();
//await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
var reJson = response.Content.ReadAsStringAsync().Result;
return reJson;
}
}
catch (Exception ex)
{
throw ex;
}
} /// <summary>
/// HttpClient实现Get请求
/// </summary>
public static string DoGet(string url)
{
try
{
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
using (var http = new HttpClient(handler))
{
var response = http.GetAsync(url).Result;
response.EnsureSuccessStatusCode();
return response.Content.ReadAsStringAsync().Result;
}
}
catch (Exception ex)
{
return ex.Message + "," + ex.Source + "," + ex.StackTrace;
}
} /// <summary>
/// HttpClient实现Get请求
/// <param name="arg">参数字典</param>
/// </summary>
public static string DoGet(string url, IDictionary<string, string> arg)
{
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
string argStr = "?";
foreach (var item in arg)
{
argStr += item.Key + "=" + item.Value + "&";
}
argStr = argStr.TrimEnd('&');
url = url + argStr;
return DoGet(url);
} /// <summary>
/// HttpClient Get 提交
/// </summary>
/// <param name="url"></param>
/// <param name="arg"></param>
/// <param name="headerDic"></param>
/// <returns></returns>
public static string DoGet(string url, IDictionary<string, string> arg, IDictionary<string, string> headerDic)
{
try
{
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
if (arg != null && arg.Count > )
{
string argStr = "?";
foreach (var item in arg)
{
argStr += item.Key + "=" + item.Value + "&";
}
argStr = argStr.TrimEnd('&');
url = url + argStr;
}
using (var http = new HttpClient(handler))
{
if (headerDic != null)
{
foreach (var item in headerDic)
{
http.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
//await异步等待回应
var response = http.GetStringAsync(url).Result;
return response;
}
}
catch (Exception ex)
{
throw ex;
}
} private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
}
}
}
单例模式 HttpClient
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using TT.Utilities.Extends;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security; namespace TT.Utilities.Web
{
public class HttpClientSingleton
{
public static readonly HttpClient http = null;
static HttpClientSingleton()
{
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
http = new HttpClient(handler);
} /// <summary>
/// post 提交json格式参数
/// </summary>
/// <param name="url">url</param>
/// <param name="postJson">json字符串</param>
/// <returns></returns>
public static string DoPost(string url, string postJson)
{
HttpContent content = new StringContent(postJson);
content.Headers.ContentType = new MediaTypeHeaderValue(HttpContentTypes.GetContentType(HttpContentTypes.HttpContentTypeEnum.JSON));
return DoPost(url, content);
} /// <summary>
/// post 提交json格式参数
/// </summary>
/// <param name="url">url</param>
/// <param name="argDic">参数字典</param>
/// <param name="headerDic">请求头字典</param>
/// <returns></returns>
public static string DoPost(string url, Dictionary<string, string> argDic, Dictionary<string, string> headerDic)
{
argDic.ToSortUrlParamString();
var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(argDic);
HttpContent content = new StringContent(jsonStr);
content.Headers.ContentType = new MediaTypeHeaderValue(HttpContentTypes.GetContentType(HttpContentTypes.HttpContentTypeEnum.JSON));
if (headerDic != null)
{
foreach (var item in headerDic)
{
content.Headers.Add(item.Key, item.Value);
}
}
return DoPost(url, content);
} /// <summary>
/// HttpClient POST 提交
/// </summary>
/// <param name="url">url</param>
/// <param name="content">HttpContent</param>
/// <returns></returns>
public static string DoPost(string url, HttpContent content)
{
try
{
var response = http.PostAsync(url, content).Result;
//确保HTTP成功状态值
response.EnsureSuccessStatusCode();
//await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
var reJson = response.Content.ReadAsStringAsync().Result;
return reJson;
}
catch (Exception ex)
{
throw ex;
}
} /// <summary>
/// HttpClient实现Get请求
/// </summary>
public static string DoGet(string url)
{
try
{
var response = http.GetAsync(url).Result;
response.EnsureSuccessStatusCode();
return response.Content.ReadAsStringAsync().Result;
}
catch (Exception ex)
{
return ex.Message + "," + ex.Source + "," + ex.StackTrace;
}
} /// <summary>
/// HttpClient实现Get请求
/// <param name="arg">参数字典</param>
/// </summary>
public static string DoGet(string url, IDictionary<string, string> arg)
{
string argStr = "?";
foreach (var item in arg)
{
argStr += item.Key + "=" + item.Value + "&";
}
argStr = argStr.TrimEnd('&');
url = url + argStr;
return DoGet(url);
} /// <summary>
/// HttpClient Get 提交
/// </summary>
/// <param name="url"></param>
/// <param name="arg"></param>
/// <param name="headerDic"></param>
/// <returns></returns>
public static string DoGet(string url, IDictionary<string, string> arg, IDictionary<string, string> headerDic)
{
try
{
if (arg != null && arg.Count > )
{
string argStr = "?";
foreach (var item in arg)
{
argStr += item.Key + "=" + item.Value + "&";
}
argStr = argStr.TrimEnd('&');
url = url + argStr;
} if (headerDic != null)
{
foreach (var item in headerDic)
{
http.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
//await异步等待回应
var response = http.GetStringAsync(url).Result;
return response; }
catch (Exception ex)
{
throw ex;
}
} private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
}
}
}
public class HttpContentTypes
{
public enum HttpContentTypeEnum
{
JSON,
FORM
} public static string GetContentType(HttpContentTypeEnum type)
{
string typeStr = "";
switch (type)
{
case HttpContentTypeEnum.JSON:
typeStr = "application/json";
break;
case HttpContentTypeEnum.FORM:
typeStr = "application/x-www-form-urlencoded";
break;
}
return typeStr;
} }
注意HttpClient的使用,推荐HttpWebRequest。
HttpWebRequest HttpClient的更多相关文章
- 关于 C# HttpClient的 请求
Efficiently Streaming Large HTTP Responses With HttpClient Downloading large files with HttpClient a ...
- Atitit s2018.5 s5 doc list on com pc.docx v2
Atitit s2018.5 s5 doc list on com pc.docx Acc 112237553.docx Acc Acc 112237553.docx Acc baidu ne ...
- 在 IIS 6 和 IIS 7中配置Https,设置WCF同时支持HTTP和HTPPS,以及使用HttpWebRequest和HttpClient调用HttpS
IIS 7 ,给IIS添加CA证书以支持https IIS 6 架设证书服务器 及 让IIS启用HTTPS服务 WCF IIS 7中配置HTTPS C#利用HttpWebRequest进行post请求 ...
- HttpWebRequest 改为 HttpClient 踩坑记-请求头设置
HttpWebRequest 改为 HttpClient 踩坑记-请求头设置 Intro 这两天改了一个项目,原来的项目是.net framework 项目,里面处理 HTTP 请求使用的是 WebR ...
- WebClient, HttpClient, HttpWebRequest ,RestSharp之间的区别与抉择
NETCore提供了三种不同类型用于生产的REST API: HttpWebRequest;WebClient;HttpClient,开源社区创建了另一个名为RestSharp的库.如此多的http库 ...
- 使用C# HttpWebRequest进行多线程网页提交。Async httpclient/HttpWebRequest实现批量任务的发布及异步提交和超时取消
使用线程池并发处理request请求及错误重试,使用委托处理UI界面输出. http://www.cnblogs.com/Charltsing/p/httpwebrequest.html for (i ...
- HttpRequest,WebRequest,HttpWebRequest,WebClient,HttpClient 之间的区别
HttpRequest,WebRequest,HttpWebRequest,WebClient,HttpClient 今天我们来聊一下他们之间的关系与区别. HttpRequest 类 .NET Fr ...
- WebRequest/HttpWebRequest/HttpRequest/WebClient/HttpClient的区别
1.WebRequest和HttpWebRequest WebRequest 的命名空间是: System.Net ,它是HttpWebRequest的抽象父类(还有其他子类如FileWebReque ...
- webrequest HttpWebRequest webclient/HttpClient
webrequest(abstract类,不可直接用) <--- (继承)---- HttpWebRequest(更好的控制请求) <--- (继承)---- webclient (简单快 ...
随机推荐
- github客户端上传代码
在window下安装github客户端上传代码 第一步:创建Github新账户 第二步:新建仓库 第三步:安装Github shell程序,地址:http://windows.github.com/ ...
- C#预处理器指令【转】
本文转载自:http://www.cnblogs.com/miffylf/p/4005223.html C#有许多名为预处理器指令的命令.这些命令从来不会转化为可执行代码中的命令,但会影响编译过程的各 ...
- POJ 1222 EXTENDED LIGHTS OUT(高斯消元)题解
题意:5*6的格子,你翻一个地方,那么这个地方和上下左右的格子都会翻面,要求把所有为1的格子翻成0,输出一个5*6的矩阵,把要翻的赋值1,不翻的0,每个格子只翻1次 思路:poj 1222 高斯消元详 ...
- 最全的Spring面试题和答案<一>
1.什么是Spring框架?Spring框架有哪些主要模块? Spring框架是一个为Java应用程序的开发提供了综合.广泛的基础性支持的Java平台.Spring帮助开发者解决了开发中基础性的问题, ...
- 使用PDFminer3k解析pdf为文字遇到:WARING:root:GBK-EUC-H
最近需要把PDF解析为文字,查了查python的模块,发现PDFminer3k能满足需求.我使用的是 windows平台下的python3.6,python2的则下载pdfminer. 首先下载:直接 ...
- 创建标签等操作DOM的原生js API
()创建新节点 createDocumentFragment() //创建一个DOM片段 createElement() //创建一个具体的元素 createTextNode() //创建一个文本节点 ...
- 使用Apache Kylin搭建企业级开源大数据分析平台
转:http://www.thebigdata.cn/JieJueFangAn/30143.html 我先做一个简单介绍我叫史少锋,我曾经在IBM.eBay做过大数据.云架构的开发,现在是Kylige ...
- Linux——帮助命令简单学习笔记
Linux帮助命令简单学习笔记: 一: 命令名称:man 命令英文原意:manual 命令所在路径:/usr/bin/man 执行权限:所有用户 语法:man [命令或配置文件] 功能描述:获得帮助信 ...
- java 从List中随机取出一个元素
java 从List中随机取出一个元素 List<Integer> list = new ArrayList<>(); Random random = new Random() ...
- Django部署生产环境,静态文件不能访问404,以及图片不能访问403
部署环境的搭建请看此博客https://blog.csdn.net/anifans9350/article/details/80145535 查看nginx.conf 文件, nginx文件(etc/ ...