You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
3.4 KiB
C#

5 months ago
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Security;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http.Headers;
namespace Infrastructure.Helpers
{
public class HttpMethods
{
//
// 摘要:
// 创建HttpClient
public static HttpClient CreateHttpClient(string url, IDictionary<string, string> cookies = null)
{
HttpClientHandler httpClientHandler = new HttpClientHandler();
Uri uri = new Uri(url);
if (cookies != null)
{
foreach (string key in cookies.Keys)
{
string cookieHeader = key + "=" + cookies[key];
httpClientHandler.CookieContainer.SetCookies(uri, cookieHeader);
}
}
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = (RemoteCertificateValidationCallback)Delegate.Combine(ServicePointManager.ServerCertificateValidationCallback, (RemoteCertificateValidationCallback)((object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslPolicyErrors) => true));
return new HttpClient(httpClientHandler);
}
return new HttpClient(httpClientHandler);
}
//
// 摘要:
// post 请求
//
// 参数:
// url:
// 请求地址
//
// jsonData:
// 请求参数
public static Task<string> Post(string url, string jsonData)
{
HttpClient httpClient = CreateHttpClient(url);
StringContent stringContent = new StringContent(jsonData);
stringContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
return httpClient.PostAsync(url, stringContent).Result.Content.ReadAsStringAsync();
}
//
// 摘要:
// post 请求
//
// 参数:
// url:
// 请求地址
public static Task<string> Post(string url)
{
HttpClient httpClient = CreateHttpClient(url);
StringContent stringContent = new StringContent("");
stringContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
return httpClient.PostAsync(url, stringContent).Result.Content.ReadAsStringAsync();
}
//
// 摘要:
// post 请求
//
// 参数:
// url:
// 请求地址
//
// req:
// 请求参数
public static Task<string> Post(string url, byte[] req)
{
HttpClient httpClient = CreateHttpClient(url);
ByteArrayContent content = new ByteArrayContent(req);
return httpClient.PostAsync(url, content).Result.Content.ReadAsStringAsync();
}
//
// 摘要:
// get 请求
//
// 参数:
// url:
// 请求地址
public static Task<string> Get(string url)
{
HttpClient httpClient = CreateHttpClient(url);
return httpClient.GetAsync(url).Result.Content.ReadAsStringAsync();
}
}
}