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. bzoj 3505 数三角形 - 组合数学

    给定一个nxm的网格,请计算三点都在格点上的三角形共有多少个.下图为4x4的网格上的一个三角形. 注意三角形的三点不能共线. Input 输入一行,包含两个空格分隔的正整数m和n. Output 输出 ...

  2. Android 自动化测试介绍

    1 介绍: 风格: 3, 4,

  3. 多线程中的信号机制--signwait()函数【转】

    本文转载自:http://blog.csdn.net/yusiguyuan/article/details/14237277 在Linux的多线程中使用信号机制,与在进程中使用信号机制有着根本的区别, ...

  4. bootstrap的 附加导航Affix导航 (侧边窄条式 滚动监控式导航) 附加导航使用3.

    affix: 意思是粘附, 附着, 沾上. 因此, 附加导航就是 bootstrap的 Affix.js组件. bootstrap的 附加导航, 不是说导航分成主导航, 或者什么 副导航的 而是指, ...

  5. bootstrap6 关于bs的使用总结

    在同一行中也可以有多个过了行的 "行", 即列的"总宽度"超宽度12. 即实现堆叠display:block和水平排列float的自动控制, 在div的clas ...

  6. Leading and Trailing(数论/n^k的前三位)题解

    Leading and Trailing You are given two integers: n and k, your task is to find the most significant ...

  7. swift设计模式学习 - 代理模式

    移动端访问不佳,请访问我的个人博客 设计模式学习的demo地址,欢迎大家学习交流 代理模式 代理模式为其他对象提供一种代理以控制对这个对象的访问,在某些情况下,一个对象不适合或者不能直接引用另一个对象 ...

  8. Sql 最简单的Sqlserver连接

    string name = txtUserName.Text.Trim();//移除用户名前部和后部的空格 string pwd = txtUserPwd.Text.Trim();//移除密码前部和后 ...

  9. 样本打散后计算单特征 NDCG

    单特征 NDCG 能计算模型的 NDCG,也就能计算单特征的 NDCG,用于评估单特征的有效性,跟 Group AUC 用途一样 单特征 NDCG 如何衡量好坏 如果是 AUC,越大于或小于 0.5, ...

  10. nginx 80 端口默认被占用

    /etc/nginx/sites-enabled,修改该目录下的default文件, 将默认端口号80改为其他端口号, /etc/nginx/nginx.conf 文件配置里的80端口就会生效