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的更多相关文章

  1. 关于 C# HttpClient的 请求

    Efficiently Streaming Large HTTP Responses With HttpClient Downloading large files with HttpClient a ...

  2. 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 ...

  3. 在 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请求 ...

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

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

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

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

  6. 使用C# HttpWebRequest进行多线程网页提交。Async httpclient/HttpWebRequest实现批量任务的发布及异步提交和超时取消

    使用线程池并发处理request请求及错误重试,使用委托处理UI界面输出. http://www.cnblogs.com/Charltsing/p/httpwebrequest.html for (i ...

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

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

  8. WebRequest/HttpWebRequest/HttpRequest/WebClient/HttpClient的区别

    1.WebRequest和HttpWebRequest WebRequest 的命名空间是: System.Net ,它是HttpWebRequest的抽象父类(还有其他子类如FileWebReque ...

  9. webrequest HttpWebRequest webclient/HttpClient

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

随机推荐

  1. noip 邮票面值设计 - 搜索 - 动态规划

    描述 给定一个信封,最多只允许粘贴N张邮票,计算在给定M(N+M<=10)种邮票的情况下(假定所有的邮票数量都足够),如何设计邮票的面值,能得到最大max ,使得1-max之间的每一个邮资值都能 ...

  2. map按value值查找——find_if的使用(转载)

    转载:http://www.cnblogs.com/xufeiyang/archive/2012/05/09/2491871.html CValueFind #ifndef _CVALUEFIND_H ...

  3. 关于Qt跨线程调用IO子类的理解

    一.疑问 突然想到,类似于QTcpsocket和QSerialport这类对象,如果是在A线程中new的,那就不能在其他线程中访问.我一般是这样做的: 封装一个QObject子类,放这些对象进去,然后 ...

  4. 【运行错误】Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.

    代码如下: <html> <head> <script> /*window.frames[]可以通过下标或名称访问单独的frame*/ window.onload= ...

  5. SRLTE,SGLTE,SVLTE,CSFB,VoLTE的区别【转】

    本文转载自:https://blog.csdn.net/dangbochang/article/details/43851979 SRLTE——Single Radio LTE,俗称单待LTE. SG ...

  6. HDU 3974 Assign the task(DFS序)题解

    题意:给出一棵树,改变树的一个节点的值,那么该节点及所有子节点都变为这个值.给出m个询问. 思路:DFS序,将树改为线性结构,用线段树维护.start[ ]记录每个节点的编号,End[ ]为该节点的最 ...

  7. 项目中同一个dll的x86和x64同时引用

    <ItemGroup Condition=" '$(Platform)' == 'x86' "> <Reference Include="System. ...

  8. Java 创建多线程的三种方法

    1. 继承Thread类2. 实现Runnable接口3. 匿名类的方式 注: 启动线程是start()方法,run()并不能启动一个新的线程

  9. Luogu P1314 聪明的质监员 二分答案

    题目链接 Solution 这个范围不是二分就是结论题就是数学题... 然后再看一会差不多就可以看出来有单调性所以就可以确定二分的解法了 二分那个$W$,用前缀和$O(n+m)$的时间来求出对答案的贡 ...

  10. 查找SQL 存储过程、触发器、视图!

    ALTER proc [dbo].[SP_SQL](@ObjectName sysname)  as  set nocount on ;  declare @Print nvarchar(max)-- ...