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. 探索Java8:Stream的使用

    Java 8 API添加了一个新的抽象称为流Stream,可以让你以一种声明的方式处理数据. Stream 使用一种类似用 SQL 语句从数据库查询数据的直观方式来提供一种对 Java 集合运算和表达 ...

  2. 全球变暖|2018年蓝桥杯B组题解析第九题-fishers

    标题:全球变暖 你有一张某海域NxN像素的照片,"."表示海洋."#"表示陆地,如下所示: ....... .##.... .##.... ....##. .. ...

  3. How to create Excel file in C#

    http://csharp.net-informations.com/excel/csharp-create-excel.htm Before you create an Excel file in ...

  4. 基础dp 记录

    51nod 1134 最长递增子序列 #include<iostream> #include<cstdio> #include<cstring> #include& ...

  5. BZOJ2982: combination Lucas

    Description LMZ有n个不同的基友,他每天晚上要选m个进行[河蟹],而且要求每天晚上的选择都不一样.那么LMZ能够持续多少个这样的夜晚呢?当然,LMZ的一年有10007天,所以他想知道答案 ...

  6. Unity3D学习笔记(六):三角函数和点乘

    三角函数: 概念:用来描述三角形中某个角和对应的三条边的比例关系. 正弦:sin<θ>(sin<theta>)=对边/斜边 余弦:cos<θ>(cos<the ...

  7. Ubuntu 14.04 python3.6 安装

    参考 how-do-i-install-python-3-6-using-apt-get Ubuntu 14.04 python3.6 安装 sudo add-apt-repository ppa:j ...

  8. python 编程基础练习 第一天

    python 编程基础练习 第一天: 需求: 1.计算2的38次方,180*0.7输出(精度显示正常), x的y次方,数字倒序输出即345876输出678543,方法越多越好. 2.字符串处理: 1) ...

  9. 纯CSS实现一个微信logo,需要几个标签?

    博客已迁移至http://lwzhang.github.io. 纯CSS实现一个微信logo并不难,难的是怎样用最少的html标签实现.我一直在想怎样用一个标签就能实现,最后还是没想出来,就只好用两个 ...

  10. 通过设置代理,解决服务器禁止抓取,报“java.io.IOException: Server returned HTTP response code: 403 for URL”错误的方法

    java.io.IOException: Server returned HTTP response code: 403 for URL: http:// 这个是什么异常呢? 当你使用java程序检索 ...