using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
namespace Pcb.Common
{
///
/// HTTP请求帮助类
///
public class HttpRequestHelper
{
///
/// Post请求
///
/// 请求地址
/// 请求参数
///
/// 流信息
public static string DoPost(string url, string postParam, string encode = "utf-8", string contentType = "application/x-www-form-urlencoded", int timeout = 100000, string authorization = "", bool isLog = false)
{
try
{
ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
var param = Encoding.GetEncoding(encode).GetBytes(postParam);
HttpWebRequest req = null;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
req = WebRequest.Create(url) as HttpWebRequest;
req.ProtocolVersion = HttpVersion.Version10;
}
else
{
req = WebRequest.Create(url) as HttpWebRequest;
}
req.Method = "POST";
req.ContentType = contentType;
req.ContentLength = param.Length;
req.KeepAlive = false;
req.Timeout = timeout;
if (!string.IsNullOrEmpty(authorization))
{
req.Headers[HttpRequestHeader.Authorization] = authorization;
}
req.ProtocolVersion = HttpVersion.Version10;
using (var reqstream = req.GetRequestStream())
{
reqstream.Write(param, 0, param.Length);
}
using (var response = (HttpWebResponse)req.GetResponse())
{
var stream = response.GetResponseStream();
if (stream == null)
return string.Empty;
var reader = new StreamReader(stream);
var data = reader.ReadToEnd();
if (isLog) { Log(url, postParam, data); }
return data;
}
}
catch (Exception ex)
{
if (isLog) { Log(url, postParam, ex); }
LogHelper.Error(ex.ToString());
}
return "";
}
///
/// 处理GET请求
///
/// 请求地址
/// 请求参数
/// 流信息
public static string DoGet(string url, string getParam, int timeout = 500000, bool isLog = false)
{
try
{
System.GC.Collect();
System.Net.ServicePointManager.DefaultConnectionLimit = 500;
if (!string.IsNullOrWhiteSpace(getParam))
{ url = url + "?" + getParam; }
var req = WebRequest.Create(url) as HttpWebRequest;
req.Method = "Get";
req.KeepAlive = false;
req.Timeout = timeout;
using (var response = (HttpWebResponse)req.GetResponse())
{
var stream = response.GetResponseStream();
if (stream == null)
return string.Empty;
var reader = new StreamReader(stream);
var data = reader.ReadToEnd();
response.Close();
if (isLog) { Log(url, getParam, data); }
return data;
}
}
catch (Exception ex)
{
if (isLog) { Log(url, getParam, ex); }
LogHelper.Error(ex.ToString());
}
return "";
}
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
// 总是接受
return true;
}
public static string HttpPost(string url, string data, IDictionary