2025-03-28 09:49:56 +08:00

380 lines
16 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace EShang.Common
{
/// <summary>
/// 通用的HTTP请求类
/// </summary>
public class HttpUtil
{
#region -> HTTP报文请求POST
/// <summary>
/// HTTP报文请求【POST】
/// </summary>
/// <param name="postDataStr">请求参数</param>
/// <param name="RequestUrl">请求url</param>
/// <param name="ContentType">资源的媒体类型默认application/x-www-form-urlencoded</param>
/// <param name="timeout">超时时间TCP连接建立的时间和整个请求完成的时间超出了设置的时间就抛出异常程序中断</param>
/// <param name="securityProtocol">服务器通信的默认安全协议众马对账通信需使用Tls12,WCF默认通道即可</param>
/// <returns></returns>
public static string HttpUrlPost(string postDataStr, string RequestUrl, string ContentType = "application/x-www-form-urlencoded",
int timeout = 0, SecurityProtocolType securityProtocol = SecurityProtocolType.SystemDefault)
{
try
{
CookieContainer cookieContainer = new CookieContainer();
byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postDataStr);
// 设置提交的相关参数
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
HttpWebRequest request = WebRequest.Create(RequestUrl) as HttpWebRequest;
if (timeout > 0)
{
request.Timeout = timeout * 1000;
}
request.Method = "POST";
request.KeepAlive = false;
request.ContentType = ContentType;
request.CookieContainer = cookieContainer;
request.ContentLength = postBytes.Length;
using (System.IO.Stream reqStream = request.GetRequestStream())
{
reqStream.Write(postBytes, 0, postBytes.Length);
}
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
//在这里对接收到的页面内容进行处理
//直到request.GetResponse()程序才开始向目标网页发送post请求
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
string val = reader.ReadToEnd();
return val;
}
}
catch (Exception ex)
{
SuperMap.RealEstate.Utility.ErrorLogHelper.Write(ex, "Post请求", "Post请求" + postDataStr + "" + RequestUrl);
return ex.ToString();
}
}
/// <summary>
/// HTTP报文请求【POST】
/// </summary>
/// <param name="jsonData">报文内容</param>
/// <param name="url">请求地址</param>
/// <param name="contentType">资源的媒体类型</param>
/// <param name="timeoutSeconds">超时时间</param>
/// <param name="acceptType">请求的接受类型</param>
/// <param name="headers">请求头</param>
/// <returns></returns>
public static string HttpUrlPost(string jsonData, string url, string contentType,
int timeoutSeconds, string acceptType, Dictionary<string, string> headers)
{
try
{
// 创建 HttpWebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST"; // 设置请求方法为 POST
request.ContentType = contentType; // 设置请求体的 ContentType
if (!string.IsNullOrWhiteSpace(acceptType))
{
request.Accept = acceptType; // 设置请求的接受类型
}
else
{
request.Accept = "*/*";
}
if (string.IsNullOrWhiteSpace(HttpContext.Current.Request.UserAgent))
{
request.UserAgent = "Windows Server2012R2;WebApi 4.0";
}
else
{
request.UserAgent = HttpContext.Current.Request.UserAgent;
}
request.Timeout = timeoutSeconds * 1000; // 设置超时时间,单位为毫秒
// 添加请求头
if (headers != null)
{
foreach (var header in headers)
{
request.Headers.Add(header.Key, header.Value);
}
}
// 写入请求体
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(jsonData);
writer.Flush();
}
// 获取响应
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// 如果请求成功,读取返回内容
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
}
catch (WebException ex)
{
// 处理错误(如超时、网络错误等)
using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream()))
{
string errorResponse = reader.ReadToEnd();
return $"Error: {ex.Message}, Response: {errorResponse}";
}
}
catch (Exception ex)
{
// 处理其他类型的异常
return $"Exception: {ex.Message}";
}
}
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
#endregion
#region -> HTTP报文请求GET
/// <summary>
/// HTTP报文请求【GET】
/// </summary>
/// <param name="RequestUrl">请求url</param>
/// <param name="ContentType">资源的媒体类型默认application/x-www-form-urlencoded</param>
/// <param name="timeout">超时时间TCP连接建立的时间和整个请求完成的时间超出了设置的时间就抛出异常程序中断</param>
/// <returns></returns>
public static string HttpUrlGet(string RequestUrl,
string ContentType = "application/x-www-form-urlencoded", int timeout = 0)
{
try
{
// 设置提交的相关参数
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
//根据url创建HttpWebRequest对象
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(RequestUrl);
objRequest.Method = "get";
objRequest.KeepAlive = false;
objRequest.ContentType = ContentType;
if (timeout > 0)
{
objRequest.Timeout = timeout * 1000;
}
//读取服务器返回信息
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
//using作为语句用于定义一个范围在此范围的末尾将释放对象
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
//ReadToEnd适用于小文件的读取一次性的返回整个文件
string Result = sr.ReadToEnd();
sr.Close();
return Result;
}
}
catch (Exception ex)
{
SuperMap.RealEstate.Utility.ErrorLogHelper.Write(ex, "Get请求", "Get请求" + RequestUrl);
return ex.ToString();
}
}
#endregion
#region -> 使Post form-data方法上传数据
/// <summary>
/// 使用Post form-data方法上传数据、文件
/// </summary>
/// <param name="url"></param>
/// <param name="formItems">Post表单内容</param>
/// <param name="cookieContainer"></param>
/// <param name="timeOut">默认20秒</param>
/// <param name="refererUrl">Referer HTTP 标头</param>
/// <param name="encoding">响应内容的编码类型默认utf-8</param>
/// <returns></returns>
public static string PostForm(string url, List<Model.FormItemModel> formItems, CookieContainer cookieContainer = null,
string refererUrl = null, Encoding encoding = null, int timeOut = 20000)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
#region
request.Method = "POST";
request.Timeout = timeOut;
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
request.KeepAlive = true;
if (string.IsNullOrWhiteSpace(HttpContext.Current.Request.UserAgent))
{
request.UserAgent = "Windows Server2012R2;WebApi 4.0";
}
else
{
request.UserAgent = HttpContext.Current.Request.UserAgent;
}
if (!string.IsNullOrEmpty(refererUrl))
{
request.Referer = refererUrl;
}
if (cookieContainer != null)
{
request.CookieContainer = cookieContainer;
}
#endregion
string boundary = "----" + DateTime.Now.Ticks.ToString("x");//分隔符
request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
//请求流
var postStream = new MemoryStream();
#region Form表单请求内容
//是否用Form上传文件
var formUploadFile = formItems != null && formItems.Count > 0;
if (formUploadFile)
{
//文件数据模板
string fileFormdataTemplate =
"\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" +
"\r\nContent-Type: application/octet-stream" +
"\r\n\r\n";
//文本数据模板
string dataFormdataTemplate =
"\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\"" +
"\r\n\r\n{1}";
foreach (var item in formItems)
{
string formdata = null;
if (item.IsFile)
{
//上传文件
formdata = string.Format(
fileFormdataTemplate,
item.Key, //表单键
item.FileName);
}
else
{
//上传文本
formdata = string.Format(
dataFormdataTemplate,
item.Key,
item.Value);
}
//统一处理
byte[] formdataBytes = null;
//第一行不需要换行
if (postStream.Length == 0)
formdataBytes = Encoding.UTF8.GetBytes(formdata.Substring(2, formdata.Length - 2));
else
formdataBytes = Encoding.UTF8.GetBytes(formdata);
postStream.Write(formdataBytes, 0, formdataBytes.Length);
//写入文件内容
if (item.FileContent != null && item.FileContent.Length > 0)
{
using (var stream = item.FileContent)
{
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
{
postStream.Write(buffer, 0, bytesRead);
}
}
}
}
//结尾
var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
postStream.Write(footer, 0, footer.Length);
}
else
{
request.ContentType = "application/x-www-form-urlencoded";
}
#endregion
request.ContentLength = postStream.Length;
#region
if (postStream != null)
{
postStream.Position = 0;
//直接写入流
Stream requestStream = request.GetRequestStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
////debug
//postStream.Seek(0, SeekOrigin.Begin);
//StreamReader sr = new StreamReader(postStream);
//var postStr = sr.ReadToEnd();
postStream.Close();//关闭文件访问
}
#endregion
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (cookieContainer != null)
{
response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
}
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.UTF8))
{
string retString = myStreamReader.ReadToEnd();
return retString;
}
}
}
#endregion
#region ->
/// <summary>
/// 请求移动业务的接口
/// </summary>
/// <param name="parameters">URL后面的参数</param>
/// <returns></returns>
public static string PostMobileService(string parameters, string provinceCode)
{
string reString = "";
try
{
string _BaseUrl = ConfigurationManager.AppSettings[provinceCode];
string RequestUrl = _BaseUrl + parameters;
reString = HttpUrlPost(parameters, RequestUrl);
}
catch (Exception ex)
{
reString = "error:" + ex.Message;
}
return reString;
}
#endregion
}
}