using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Net.Cache;
using System.Reflection;
using System.Text;
using IwbZero.ToolCommon.LogHelpers;
using IwbZero.ToolCommon.StringModel;
namespace IwbZero.ToolCommon
{
public static class HttpHelper
{
#region POST
///
/// POST请求
///
///
///
///
///
///
///
public static string RequestPost(this string url, string dataStr, string authKey = null, string callBackUrl = "", string contentType = null)
{
ServicePointManager.DefaultConnectionLimit = 512;
string respResult = null;
HttpWebRequest req = null;
try
{
req = GeneratePostWebRequest(url, dataStr, contentType);
if (!string.IsNullOrEmpty(authKey))
{
var base64Str = authKey.EncodeBase64();
SetHeaderValue(req.Headers, "Authorization", "Bearer " + base64Str);
typeof(HttpHelper).LogWarn($"[Authorization]-[{authKey}]-[Bearer {base64Str}]");
}
if (!string.IsNullOrEmpty(callBackUrl))
{
var base64Str = callBackUrl.EncodeBase64();
SetHeaderValue(req.Headers, "CallBackUrl", base64Str);
typeof(HttpHelper).LogWarn($"[CallBackUrl]-[{callBackUrl}]-[ {base64Str}]");
}
respResult = GenerateWebResponse(req);
}
catch (Exception eee)
{
typeof(HttpHelper).LogWarn("[Error]" + eee + eee.Source + eee.StackTrace);
}
finally
{
req?.Abort();
}
return respResult;
}
///
/// POST请求
///
///
///
/// 头部信息字典
///
///
public static string RequestPost(this string url, string dataStr, Dictionary dicHeader, string contentType = null)
{
ServicePointManager.DefaultConnectionLimit = 512;
string respResult = null;
HttpWebRequest req = null;
try
{
req = GeneratePostWebRequest(url, dataStr, contentType);
if (dicHeader != null)
{
foreach (var dic in dicHeader)
{
if (dic.Value.IsEmpty())
{
continue;
}
var base64Str = dic.Value.EncodeBase64();
if (dic.Key.UAndT() == "AuthKey".UAndT() || dic.Key.UAndT() == "Auth".UAndT() || dic.Key.UAndT() == "Authorization".UAndT())
{
SetHeaderValue(req.Headers, "Authorization", "Bearer " + base64Str);
}
else
{
SetHeaderValue(req.Headers, dic.Key, base64Str);
}
}
}
respResult = GenerateWebResponse(req);
}
catch (Exception eee)
{
typeof(HttpHelper).LogWarn("[Error]" + eee + eee.Source + eee.StackTrace);
}
finally
{
req?.Abort();
}
return respResult;
}
///
/// POST请求
///
///
///
/// 加载头部信息委托
///
///
public static string RequestPost(this string url, string dataStr, Func headerFunc, string contentType = null)
{
ServicePointManager.DefaultConnectionLimit = 512;
string respResult = null;
HttpWebRequest req = null;
try
{
req = GeneratePostWebRequest(url, dataStr, contentType);
req = headerFunc.Invoke(req);
respResult = GenerateWebResponse(req);
}
catch (Exception eee)
{
typeof(HttpHelper).LogWarn("[Error]" + eee + eee.Source + eee.StackTrace);
}
finally
{
req?.Abort();
}
return respResult;
}
#endregion
#region GET
///
/// GET请求
///
///
///
///
///
///
///
public static string RequestGet(this string url, string dataStr, string authKey = null, string callBackUrl = "", string contentType = null)
{
ServicePointManager.DefaultConnectionLimit = 512;
string respResult = null;
HttpWebRequest req = null;
try
{
req = GenerateGetWebRequest(url, contentType);
if (!string.IsNullOrEmpty(authKey))
{
var base64Str = authKey.EncodeBase64();
SetHeaderValue(req.Headers, "Authorization", "Bearer " + base64Str);
typeof(HttpHelper).LogWarn($"[Authorization]-[{authKey}]-[Bearer {base64Str}]");
}
if (!string.IsNullOrEmpty(callBackUrl))
{
var base64Str = callBackUrl.EncodeBase64();
SetHeaderValue(req.Headers, "CallBackUrl", base64Str);
typeof(HttpHelper).LogWarn($"[CallBackUrl]-[{callBackUrl}]-[ {base64Str}]");
}
respResult = GenerateWebResponse(req);
}
catch (Exception eee)
{
typeof(HttpHelper).LogWarn("[Error]" + eee + eee.Source + eee.StackTrace);
}
finally
{
req?.Abort();
}
return respResult;
}
///
/// GET请求
///
///
///
/// 头部信息字典
///
///
public static string RequestGet(this string url, string dataStr, Dictionary dicHeader, string contentType = null)
{
ServicePointManager.DefaultConnectionLimit = 512;
string respResult = null;
HttpWebRequest req = null;
try
{
req = GenerateGetWebRequest(url, contentType);
if (dicHeader != null)
{
foreach (var dic in dicHeader)
{
if (dic.Value.IsEmpty())
{
continue;
}
var base64Str = dic.Value.EncodeBase64();
if (dic.Key.UAndT() == "AuthKey".UAndT() || dic.Key.UAndT() == "Auth".UAndT() || dic.Key.UAndT() == "Authorization".UAndT())
{
SetHeaderValue(req.Headers, "Authorization", "Bearer " + base64Str);
}
else
{
SetHeaderValue(req.Headers, dic.Key, base64Str);
}
}
}
respResult = GenerateWebResponse(req);
}
catch (Exception eee)
{
typeof(HttpHelper).LogWarn("[Error]" + eee + eee.Source + eee.StackTrace);
}
finally
{
req?.Abort();
}
return respResult;
}
///
/// GET请求
///
///
///
/// 加载头部信息委托
///
///
public static string RequestGet(this string url, string dataStr, Func headerFunc, string contentType = null)
{
ServicePointManager.DefaultConnectionLimit = 512;
string respResult = null;
HttpWebRequest req = null;
try
{
req = GenerateGetWebRequest(url, contentType);
req = headerFunc.Invoke(req);
respResult = GenerateWebResponse(req);
}
catch (Exception eee)
{
typeof(HttpHelper).LogWarn("[Error]" + eee + eee.Source + eee.StackTrace);
}
finally
{
req?.Abort();
}
return respResult;
}
#endregion
///
/// 设置头部信息
///
///
///
///
public static void SetHeaderValue(WebHeaderCollection header, string name, string value)
{
var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", BindingFlags.Instance | BindingFlags.NonPublic);
if (property != null)
{
if (property.GetValue(header, null) is NameValueCollection collection)
collection[name] = value;
}
}
#region 私有方法
///
/// 创建POST请求
///
///
///
///
///
private static HttpWebRequest GeneratePostWebRequest(string url, string dataStr, string contentType = null)
{
typeof(HttpHelper).LogWarn($"[POST]-[{url}]-[{dataStr}]");
GC.Collect();
Uri uri = new Uri(url);
ServicePoint spSite = ServicePointManager.FindServicePoint(uri);
spSite.ConnectionLimit = 50;
var req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = contentType ?? "application/json";
req.Accept = "*/*";
req.Timeout = 5 * 60 * 60 * 1000;
req.UserAgent = "Mozilla-Firefox";
//这个在Post的时候,一定要加上,如果服务器返回错误,他还会继续再去请求,不会使用之前的错误数据,做返回数据
req.ServicePoint.Expect100Continue = false;
HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
req.CachePolicy = noCachePolicy;
RequestWriteData(ref req, dataStr);
return req;
}
///
/// 创建GET请求
///
///
///
///
private static HttpWebRequest GenerateGetWebRequest(string url, string contentType = null)
{
GC.Collect();
Uri uri = new Uri(url);
ServicePoint spSite = ServicePointManager.FindServicePoint(uri);
spSite.ConnectionLimit = 50;
var req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = contentType ?? "application/json";
req.Accept = "*/*";
req.Timeout = 5 * 60 * 60 * 1000;
req.UserAgent = "Mozilla-Firefox";
//这个在Post的时候,一定要加上,如果服务器返回错误,他还会继续再去请求,不会使用之前的错误数据,做返回数据
req.ServicePoint.Expect100Continue = false;
HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
req.CachePolicy = noCachePolicy;
return req;
}
///
/// 请求加载数据
///
///
///
private static void RequestWriteData(ref HttpWebRequest req, string dataStr)
{
Stream streamSend = null;
try
{
if (dataStr.IsNotEmpty())
{
byte[] data = Encoding.UTF8.GetBytes(dataStr);
req.ContentLength = data.Length;
streamSend = req.GetRequestStream();
streamSend.Write(data, 0, data.Length);
streamSend.Close();
}
else
{
req.ContentLength = 0;
}
}
catch (WebException wex)
{
typeof(HttpHelper).LogWarn("[Error]-[WebException]-" + wex + ",wex.Status=" + wex.Status);
//return null;
}
catch (Exception ex)
{
typeof(HttpHelper).LogWarn("[Error]-[GetRequestStream]-" + ex);
//return null;
}
finally
{
streamSend?.Close();
}
//return req;
}
///
/// 响应解析
///
///
///
private static string GenerateWebResponse(HttpWebRequest req)
{
string respResult = "";
try
{
WebResponse rsp = req.GetResponse() as HttpWebResponse;
respResult = GetResponseStr(rsp);
typeof(HttpHelper).LogWarn($"End- WITH:[{respResult}]");
}
catch (WebException webEx)
{
respResult = GetResponseStr(webEx.Response);
typeof(HttpHelper).LogWarn($"End- WITH:[{respResult}]");
return respResult;
}
catch (Exception ex)
{
typeof(HttpHelper).LogWarn("[Error]-[SendRequest]-" + ex);
return respResult;
}
return respResult;
}
///
/// 读取响应字符串
///
///
///
private static string GetResponseStr(WebResponse rsp)
{
Stream streamRequest = null;
try
{
string respResult = "";
streamRequest = rsp?.GetResponseStream();
if (streamRequest != null)
using (StreamReader reader = new StreamReader(streamRequest))
{
respResult = reader.ReadToEnd();
}
return respResult;
}
finally
{
streamRequest?.Close();
}
}
#endregion
//public static string SendRequest(this string url, string dataStr, string callBackUrl = "", string authKey = null, string contentType = null)
//{
// ServicePointManager.DefaultConnectionLimit = 512;
// string respResult = null;
// HttpWebRequest req = null;
// typeof(HttpHelper).LogWarn($"Start-[{url}-Back:{callBackUrl}] WITH:[{dataStr}]");
// try
// {
// GC.Collect();
// Uri uri = new Uri(url);
// ServicePoint spSite = ServicePointManager.FindServicePoint(uri);
// spSite.ConnectionLimit = 50;
// Stream streamSend = null;
// req = (HttpWebRequest)WebRequest.Create(url);
// req.Method = "POST";
// if (!string.IsNullOrEmpty(authKey))
// {
// var base64Str = authKey.EncodeBase64();
// SetHeaderValue(req.Headers, "Authorization", "Bearer " + base64Str);
// typeof(HttpHelper).LogWarn($"[Authorization]-[{authKey}]-[Bearer {base64Str}]");
// }
// if (!string.IsNullOrEmpty(callBackUrl))
// {
// var base64Str = callBackUrl.EncodeBase64();
// SetHeaderValue(req.Headers, "CallBackUrl", base64Str);
// typeof(HttpHelper).LogWarn($"[Authorization]-[{authKey}]-[Bearer {base64Str}]");
// }
// req.ContentType = contentType ?? "application/json";
// req.Accept = "*/*";
// req.Timeout = 5 * 60 * 60 * 1000;
// req.UserAgent = "Mozilla-Firefox";
// //这个在Post的时候,一定要加上,如果服务器返回错误,他还会继续再去请求,不会使用之前的错误数据,做返回数据
// req.ServicePoint.Expect100Continue = false;
// HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
// req.CachePolicy = noCachePolicy;
// try
// {
// byte[] data = Encoding.UTF8.GetBytes(dataStr);
// req.ContentLength = data.Length;
// streamSend = req.GetRequestStream();
// streamSend.Write(data, 0, data.Length);
// streamSend.Close();
// }
// catch (WebException wex)
// {
// typeof(HttpHelper).LogWarn("[Error]-[WebException]-" + wex + ",wex.Status=" + wex.Status);
// streamSend?.Close();
// return null;
// }
// catch (Exception ex)
// {
// typeof(HttpHelper).LogWarn("[Error]-[GetRequestStream]-" + ex);
// streamSend?.Close();
// return null;
// }
// finally
// {
// streamSend.Close();
// }
// try
// {
// respResult = GenerateWebResponse(req);
// typeof(HttpHelper).LogWarn($"End- WITH:[{respResult}]");
// }
// catch (WebException httpwex)
// {
// //typeof(HttpRequestHelper).LogWarn("[Error]-[WebException]-" + httpwex + ",wex.Status=" + httpwex.Status);
// respResult = GetResponseStr(httpwex.Response);
// typeof(HttpHelper).LogWarn($"End- WITH:[{respResult}]");
// return respResult;
// }
// catch (Exception httpex)
// {
// typeof(HttpHelper).LogWarn("[Error]-[SendRequest]-" + httpex);
// return respResult;
// }
// }
// catch (Exception eee)
// {
// typeof(HttpHelper).LogWarn("[Error]" + eee + eee.Source + eee.StackTrace);
// }
// finally
// {
// req?.Abort();
// }
// return respResult;
//}
/////
///// Http Get Request
/////
/////
/////
//public static string HttpGet(this string url)
//{
// string strGetResponse;
// try
// {
// var getRequest = CreateHttpRequest(url, "GET");
// var getResponse = getRequest.GetResponse() as HttpWebResponse;
// strGetResponse = GetHttpResponse(getResponse, "GET");
// }
// catch (Exception ex)
// {
// strGetResponse = ex.Message;
// }
// return strGetResponse;
//}
/////
///// Http Get Request Async
/////
/////
//public static async void HttpGetAsync(this string url)
//{
// string strGetResponse;
// try
// {
// var getRequest = CreateHttpRequest(url, "GET");
// var getResponse = await getRequest.GetResponseAsync() as HttpWebResponse;
// strGetResponse = GetHttpResponse(getResponse, "GET");
// }
// catch (Exception ex)
// {
// strGetResponse = ex.Message;
// }
// // return strGetResponse;
// Console.WriteLine("reslut:" + strGetResponse);
//}
/////
///// Http Post Request
/////
/////
/////
/////
/////
//public static string HttpPost(this string url, string postData, string contentType = null)
//{
// int random = new Random().Next(0, 10000);
// typeof(HttpHelper).LogWarn("-->[" + random + "]StartWith : " + url + " [ data:" + postData + "]");
// string strPostReponse;
// HttpWebResponse postResponse = null;
// HttpWebRequest postRequest = null;
// try
// {
// postRequest = CreateHttpRequest(url, "POST", postData, contentType);
// postResponse = postRequest.GetResponse() as HttpWebResponse;
// strPostReponse = GetHttpResponse(postResponse, "POST");
// }
// catch (Exception ex)
// {
// strPostReponse = ex.Message;
// }
// finally
// {
// postRequest?.Abort();
// postResponse?.Close();
// }
// typeof(HttpHelper).LogWarn("-->[" + random + "]EndWith : " + strPostReponse);
// return strPostReponse;
//}
/////
///// Http Post Request Async
/////
/////
/////
/////
//public static async Task HttpPostAsync(this string url, string postData, string contentType = null)
//{
// int random = new Random().Next(0, 10000);
// typeof(HttpHelper).LogWarn("-->[" + random + "]StartWith : " + url + " [ data:" + postData + "]");
// string strPostReponse;
// try
// {
// var postRequest = CreatePostHttpWebRequest(url, postData, contentType);
// var postResponse = await postRequest.GetResponseAsync() as HttpWebResponse;
// strPostReponse = GetHttpResponse(postResponse, "POST");
// }
// catch (Exception ex)
// {
// strPostReponse = ex.Message;
// }
// typeof(HttpHelper).LogWarn("-->[" + random + "]EndWith : " + strPostReponse);
// return strPostReponse;
//}
//private static HttpWebRequest CreateHttpRequest(string url, string requestType, params object[] strJson)
//{
// HttpWebRequest request = null;
// const string get = "GET";
// const string post = "POST";
// if (string.Equals(requestType, get, StringComparison.OrdinalIgnoreCase))
// {
// request = CreateGetHttpWebRequest(url);
// }
// if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase))
// {
// request = CreatePostHttpWebRequest(url, strJson[0].ToString());
// }
// return request;
//}
//private static HttpWebRequest CreateGetHttpWebRequest(string url)
//{
// var getRequest = (HttpWebRequest)WebRequest.Create(url);
// getRequest.Method = "GET";
// getRequest.Timeout = 5000;
// getRequest.ContentType = "text/html;charset=UTF-8";
// getRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
// return getRequest;
//}
//private static HttpWebRequest CreatePostHttpWebRequest(string url, string postData, string contentType = null)
//{
// GC.Collect();
// //ServicePointManager.DefaultConnectionLimit = 10;
// var postRequest = (HttpWebRequest)WebRequest.Create(url);
// postRequest.ServicePoint.Expect100Continue = false;
// postRequest.KeepAlive = false;
// postRequest.Timeout = 5000;
// postRequest.Method = "POST";
// postRequest.ContentType = contentType ?? "application/json";//"application/x-www-form-urlencoded";
// postRequest.AllowWriteStreamBuffering = false;
// byte[] data = Encoding.UTF8.GetBytes(postData);
// postRequest.ContentLength = data.Length;
// Stream newStream = postRequest.GetRequestStream();
// newStream.Write(data, 0, data.Length);
// newStream.Close();
// //StreamWriter writer = new StreamWriter(postRequest.GetRequestStream(), Encoding.ASCII);
// //writer.Write(postData);
// //writer.Flush();
// return postRequest;
//}
//private static string GetHttpResponse(HttpWebResponse response, string requestType)
//{
// const string post = "POST";
// string encoding = "UTF-8";
// if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase))
// {
// encoding = response.ContentEncoding;
// if (encoding.Length < 1)
// {
// encoding = "UTF-8";
// }
// }
// string responseResult;
// using (StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.GetEncoding(encoding)))
// {
// responseResult = reader.ReadToEnd();
// }
// return responseResult;
//}
/////
///// Base64 编码
/////
///// 编码方式
///// 要编码的字符串
///// 返回编码后的字符串
//public static string EncodeBase64(this string source, Encoding encode = null)
//{
// string result;
// try
// {
// encode = encode ?? Encoding.UTF8;
// byte[] bytes = encode.GetBytes(source);
// result = Convert.ToBase64String(bytes);
// }
// catch
// {
// result = source;
// }
// return result;
//}
/////
///// Base64 解码
/////
///// 解码方式
///// 要解码的字符串
///// 返回解码后的字符串
//public static string DecodeBase64(this string source, Encoding encode = null)
//{
// string result;
// try
// {
// byte[] bytes = Convert.FromBase64String(source);
// encode = encode ?? Encoding.UTF8;
// result = encode.GetString(bytes);
// }
// catch
// {
// result = source;
// }
// return result;
//}
}
}