这是项目中一个封装的请求帮组类,非常实用。现在分享出来,也是笔记,方便以后查找。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace SignDemo.UtilHelp
{
public static class HttpHelperService
{
/// <summary>
/// 异步方法
/// </summary>
/// <param name="url"></param>
/// <param name="Timeout"></param>
/// <param name="method"></param>
/// <returns></returns>
public static async Task<string> SendHttpRequestAsync(string url, string Body = "", string contentType = null, Dictionary<string, string> headers = null, int Timeout = 30)
{
byte[] sendData = Encoding.UTF8.GetBytes(Body);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Timeout = Timeout; // 设置超时时间
if (contentType != null)
{
request.ContentType = contentType;
}
if (headers != null)
{
foreach (var header in headers)
{
request.Headers.Add(header.Key, header.Value);
}
}
using (Stream sendStream = request.GetRequestStream())
{
sendStream.Write(sendData, 0, sendData.Length);
sendStream.Close();
}
using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse)
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
return await reader.ReadToEndAsync();
}
}
}
/// <summary>
/// 同步方法
/// </summary>
/// <param name="url"></param>
/// <param name="Timeout"></param>
/// <param name="method"></param>
/// <returns></returns>
public static string SendHttpRequest2(string url, string Body = "", string contentType = null, Dictionary<string, string> headers = null, int Timeout = 30)
{
byte[] sendData = Encoding.UTF8.GetBytes(Body);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Timeout = Timeout; // 设置超时时间
if (contentType != null)
{
request.ContentType = contentType;
}
if (headers != null)
{
foreach (var header in headers)
{
request.Headers.Add(header.Key, header.Value);
}
}
// request.Headers.Add("app_id", "NTEST");
// request.Headers.Add("app_key", "eef7b688-19c4-433b-94f1-300523964f2f");
using (Stream sendStream = request.GetRequestStream())
{
sendStream.Write(sendData, 0, sendData.Length);
sendStream.Close();
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
}
public static HttpWebResponse SendHttpRequest(string url, string Body = "", string contentType = null, Dictionary<string, string> headers = null, int Timeout = 3000)
{
byte[] sendData = Encoding.UTF8.GetBytes(Body);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Timeout = Timeout; // 设置超时时间
if (contentType != null)
{
request.ContentType = contentType;
}
if (headers != null)
{
foreach (var header in headers)
{
request.Headers.Add(header.Key, header.Value);
}
}
using (Stream sendStream = request.GetRequestStream())
{
sendStream.Write(sendData, 0, sendData.Length);
sendStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return response;
}
public static string SendHttpRequest3(string url, string Body = "", string contentType = "application/x-www-form-urlencoded", int Timeout = 3000)
{
byte[] sendData = Encoding.UTF8.GetBytes(HttpUtility.UrlEncode(Body));//加了一层编码
// byte[] sendData = Encoding.UTF8.GetBytes(Body);//加了一层编码
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Timeout = Timeout; // 设置超时时间
if (contentType != null)
{
request.ContentType = contentType;
}
using (Stream sendStream = request.GetRequestStream())
{
sendStream.Write(sendData, 0, sendData.Length);
sendStream.Close();
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
}
/// <summary>
/// 设置证书策略
/// </summary>
public static void SetCertificatePolicy()
{
System.Net.ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
}
/// <summary>
/// Remotes the certificate validate.
/// </summary>
private static bool RemoteCertificateValidate(
object sender, X509Certificate cert,
X509Chain chain, SslPolicyErrors error)
{
return true;
}
public static string HttpPost(string url, string body = null, string contentType = null, int timeOut = 3000)
{
// body = body ?? "";
SetCertificatePolicy();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (HttpClient client = new HttpClient())
{
client.Timeout = new TimeSpan(0, 0, timeOut);
using (HttpContent httpContent = new StringContent(UrlEncodeToJava(body), Encoding.UTF8))
{
if (contentType != null)
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
}
public static string HttpPost2(string url, string body = null, string contentType = null, Dictionary<string, string> headers = null, int timeOut = 30)
{
body = body ?? "";
SetCertificatePolicy();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (HttpClient client = new HttpClient())
{
client.Timeout = new TimeSpan(0, 0, timeOut);
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
using (HttpContent httpContent = new StringContent(body, Encoding.UTF8))
{
if (contentType != null)
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
}
/// <summary>
/// 发票修改请求专用
/// </summary>
/// <param name="url"></param>
/// <param name="body"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <param name="timeOut"></param>
/// <param name="accessToken"></param>
/// <returns></returns>
public static string HttpPutEInvoice(string url, string body = null, string contentType = null, Dictionary<string, string> headers = null, int timeOut = 30, string accessToken = "")
{
body = body ?? "";
SetCertificatePolicy();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (HttpClient client = new HttpClient())
{
client.Timeout = new TimeSpan(0, 0, timeOut);
if (headers != null)
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}
using (HttpContent httpContent = new StringContent(body, Encoding.UTF8))
{
if (contentType != null)
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
HttpResponseMessage response = client.PutAsync(url, httpContent).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
}
public static HttpResponseMessage HttpPutEInvoiceX(string url, string body = null, string contentType = null, Dictionary<string, string> headers = null, int timeOut = 30, string accessToken = "")
{
body = body ?? "";
SetCertificatePolicy();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (HttpClient client = new HttpClient())
{
client.Timeout = new TimeSpan(0, 0, timeOut);
if (headers != null)
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}
using (HttpContent httpContent = new StringContent(body, Encoding.UTF8))
{
if (contentType != null)
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
HttpResponseMessage response = client.PutAsync(url, httpContent).Result;
return response;
}
}
}
/// <summary>
/// 发票请求专用方法
/// </summary>
/// <param name="url"></param>
/// <param name="body"></param>
/// <param name="contentType"></param>
/// <param name="headers"></param>
/// <param name="timeOut"></param>
/// <param name="accessToken"></param>
/// <returns></returns>
public static string HttpPostEInvoice(string url, string body = null, string contentType = null, Dictionary<string, string> headers = null, int timeOut = 30, string accessToken = "")
{
body = body ?? "";
SetCertificatePolicy();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (HttpClient client = new HttpClient())
{
client.Timeout = new TimeSpan(0, 0, timeOut);
if (headers != null)
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}
using (HttpContent httpContent = new StringContent(body, Encoding.UTF8))
{
if (contentType != null)
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
}
public static HttpResponseMessage HttpPostEInvoiceX(string url, string body = null, string contentType = null, Dictionary<string, string> headers = null, int timeOut = 30, string accessToken = "")
{
body = body ?? "";
SetCertificatePolicy();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (HttpClient client = new HttpClient())
{
client.Timeout = new TimeSpan(0, 0, timeOut);
if (headers != null)
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}
using (HttpContent httpContent = new StringContent(body, Encoding.UTF8))
{
if (contentType != null)
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
return response;
}
}
}
/// <summary>
/// 发起GET同步请求
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="headers">请求头</param>
/// <param name="timeOut">超时时间</param>
/// <returns></returns>
public static string HttpGetEInvoice(string url, Dictionary<string, string> headers = null, int timeOut = 30, string accessToken = "")
{
SetCertificatePolicy();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (HttpClient client = new HttpClient())
{
client.Timeout = new TimeSpan(0, 0, timeOut);
if (headers != null)
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}
HttpResponseMessage response = client.GetAsync(url).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
public static HttpResponseMessage HttpGetEInvoiceX(string url, Dictionary<string, string> headers = null, int timeOut = 30, string accessToken = "")
{
SetCertificatePolicy();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (HttpClient client = new HttpClient())
{
client.Timeout = new TimeSpan(0, 0, timeOut);
if (headers != null)
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}
HttpResponseMessage response = client.GetAsync(url).Result;
return response;
}
}
public static string HttpPATCH(string url, string body = null, string contentType = null, Dictionary<string, string> headers = null, int timeOut = 30)
{
body = body ?? "";
SetCertificatePolicy();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (HttpClient client = new HttpClient())
{
client.Timeout = new TimeSpan(0, 0, timeOut);
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
using (HttpContent httpContent = new StringContent(body, Encoding.UTF8))
{
if (contentType != null)
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("PATCH"), url);
request.Content = httpContent;
HttpResponseMessage response = client.SendAsync(request).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
}
// 对转码后的字符进行大写转换,不会把参数转换成大写
public static string UrlEncodeToJava(string source)
{
StringBuilder builder = new StringBuilder();
foreach (char c in source)
{
if (HttpUtility.UrlEncode(c.ToString(), Encoding.UTF8).Length > 1)
{
builder.Append(HttpUtility.UrlEncode(c.ToString(), Encoding.UTF8).ToUpper());
}
else
{
builder.Append(c);
}
}
string encodeUrl = builder.ToString().Replace("(", "%28").Replace(")", "%29");
return encodeUrl;
}
public static string SendHttpRequest33(string url, string Body = "", string contentType = "application/x-www-form-urlencoded", int Timeout = 3000)
{
byte[] sendData = Encoding.UTF8.GetBytes(Body);//加了一层编码
// byte[] sendData = Encoding.UTF8.GetBytes(Body);//加了一层编码
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Timeout = Timeout; // 设置超时时间
//if (contentType != null)
//{
// request.ContentType = contentType;
//}
using (Stream sendStream = request.GetRequestStream())
{
sendStream.Write(sendData, 0, sendData.Length);
sendStream.Close();
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
}
public static string HttpPostCaiNiao(string url, SortedDictionary<string, string> dictionary, string contentType = null, Dictionary<string, string> headers = null, int timeOut = 3000)
{
using (HttpClient client = new HttpClient())
{
client.Timeout = new TimeSpan(0, 0, timeOut);
if (headers != null)
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
using (HttpContent httpContent = new FormUrlEncodedContent(dictionary))
{
if (contentType != null)
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
}
}
}
获取响应头信息,这个问了gpt平台,然后给出的答案,不过不够完整,如果里面没有那些关键词,就会报错。
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Get, "your_url_here");
request.Headers.Add("correlationId", "your_correlation_id");
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
string contentType = response.Content.Headers.ContentType.ToString();
string correlationId = response.RequestMessage.Headers.GetValues("correlationId").FirstOrDefault();
string rateLimitLimit = response.Headers.GetValues("X-Rate-Limit-Limit").FirstOrDefault();
string rateLimitRemaining = response.Headers.GetValues("X-Rate-Limit-Remaining").FirstOrDefault();
string rateLimitReset = response.Headers.GetValues("X-Rate-Limit-Reset").FirstOrDefault();
Console.WriteLine("Content-Type: " + contentType);
Console.WriteLine("CorrelationId: " + correlationId);
Console.WriteLine("X-Rate-Limit-Limit: " + rateLimitLimit);
Console.WriteLine("X-Rate-Limit-Remaining: " + rateLimitRemaining);
Console.WriteLine("X-Rate-Limit-Reset: " + rateLimitReset);
string responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
else
{
Console.WriteLine("Error: " + response.StatusCode);
}
}
}
}
避免报错处理,增加了一层判断,这样完美。
public class HeadersResModel
{
public string correlationId { get; set; }
public string requestTimeUTC { get; set; }
public string responseProcessingTimeInTicks { get; set; }
/// <summary>
/// 剩余次数
/// </summary>
public int XRateLimitRemaining { get; set; }
/// <summary>
/// 限制请求的次数
/// </summary>
public int XRateLimitLimit { get; set; }
/// <summary>
/// 限制到时间
/// </summary>
public string XRateLimitReset { get; set; }
}
private HeadersResModel GetHeadersModel(HttpResponseMessage response)
{
string correlationId = "";
string requestTimeUTC = "";
string rateLimitLimit = "-1";//默认-1
string rateLimitRemaining ="-1";
string rateLimitReset="";
string responseProcessingTimeInTicks = "";
//if (response.Headers.Contains("X-SimplyPost-Id"))
// rateLimitReset = response.Headers.GetValues("X-Rate-Limit-Reset").FirstOrDefault();
//}
if (response.Headers.Contains("correlationId"))
{
correlationId = response.Headers.GetValues("correlationId").FirstOrDefault();
}
if (response.Headers.Contains("requestTimeUTC"))
{
requestTimeUTC = response.Headers.GetValues("requestTimeUTC").FirstOrDefault();
}
if (response.Headers.Contains("X-Rate-Limit-Limit"))
{
rateLimitLimit = response.Headers.GetValues("X-Rate-Limit-Limit").FirstOrDefault();
}
if (response.Headers.Contains("X-Rate-Limit-Remaining"))
{
rateLimitRemaining = response.Headers.GetValues("X-Rate-Limit-Remaining").FirstOrDefault();
}
if (response.Headers.Contains("X-Rate-Limit-Reset"))
{
rateLimitReset = response.Headers.GetValues("X-Rate-Limit-Reset").FirstOrDefault();
}
if (response.Headers.Contains("responseProcessingTimeInTicks"))
{
rateLimitReset = response.Headers.GetValues("responseProcessingTimeInTicks").FirstOrDefault();
}
HeadersResModel model = new HeadersResModel();
model.correlationId = correlationId;
model.requestTimeUTC = requestTimeUTC;
model.XRateLimitRemaining = Convert.ToInt32(rateLimitRemaining);//限制剩余次数
model.XRateLimitLimit = Convert.ToInt32(rateLimitLimit);//限制总次数
model.XRateLimitReset = rateLimitReset;
model.responseProcessingTimeInTicks = responseProcessingTimeInTicks;
return model;
}
对于contentType是application/x-www-form-urlencoded的请求
public static string HttpPost10(string url, SortedDictionary<string, string> dictionary, string contentType = null, Dictionary<string, string> headers = null, int timeOut = 3000)
{
SetCertificatePolicy();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (HttpClient client = new HttpClient())
{
client.Timeout = new TimeSpan(0, 0, timeOut);
if (headers != null)
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
using (HttpContent httpContent = new FormUrlEncodedContent(dictionary))
{
if (contentType != null)
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
}