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 (简单快 ...
随机推荐
- 从一道题看线程安全--牛客网Java基础题
从一道题看线程安全 Java中的线程安全是什么: 就是线程同步的意思,就是当一个程序对一个线程安全的方法或者语句进行访问的时候,其他的不能再对他进行操作了,必须等到这次访问结束以后才能对这个线程安全的 ...
- Java String常见面试题汇总
String类型的面试题 1. String是最基本的数据类型吗? 基本数据类型包括byte,int,char,long,float,double,boolean,short一共八个. ...
- Python3基础 file seek 将文件的指针恢复到初始位置
Python : 3.7.0 OS : Ubuntu 18.04.1 LTS IDE : PyCharm 2018.2.4 Conda ...
- Linux内存管理--用户空间和内核空间【转】
本文转载自:http://blog.csdn.net/yusiguyuan/article/details/12045255 关于虚拟内存有三点需要注意: 4G的进程地址空间被人为的分为两个部分--用 ...
- uboot下的命令使用示例
1.usb 可以使用此命令读取u盘里的内容,此命令加上相关参数可以有以下功能: 1.1usb start 在使用u盘之前必须启动此命令以初始化好fat文件系统环境,笔者的输出如下: jello # u ...
- [BZOJ1103][POI2007]大都市meg dfs序+树状数组
Description 在经济全球化浪潮的影响下,习惯于漫步在清晨的乡间小路的邮递员Blue Mary也开始骑着摩托车传递邮件了.不过,她经常回忆起以前在乡间漫步的情景.昔日,乡下有依次编号为1..n ...
- 【TCP/IP详解 卷一:协议】第二十章 TCP的成块数据流
本章节主要内容: ACK的累积 滑动窗口协议(即 接收方TCP数据报缓存的大小) 流量控制(慢启动 -发送方TCP的 拥塞窗口(cwnd) 以及接受方的 通告窗口) 20.1 引言 在教材的之前章节中 ...
- 【Coursera】Security Introduction -Ninth Week(2)
对于公钥系统,我们现在已经有了保证它 Confidentially 的一种方法:SSL.SSL利用了公钥的概念. 那么 who we are talking to? Integrity Certifi ...
- UVa 1603 破坏正方形
https://vjudge.net/problem/UVA-1603 题意:有一个火柴棍组成的正方形网格,计算至少要拿走多少根火柴才能破坏所有正方形. 思路:从边长为1的正方形开始遍历,将正方形的边 ...
- ubuntu server 多网卡
https://wenku.baidu.com/view/51fb15742f60ddccdb38a007.html