| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Business.Core.Utilities
- {
- public class HttpHelper
- {/// <summary>
- /// 发起POST同步请求
- ///
- /// </summary>
- /// <param name="url"></param>
- /// <param name="postData"></param>
- /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
- /// <param name="headers">填充消息头</param>
- /// <returns></returns>
- public static string HttpPost(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null)
- {
- public static string HttpGet(string url, Dictionary<string, string>? headers = null)
- {
- HttpClient client = new HttpClient();
- if (headers != null)
- {
- foreach (var header in headers)
- {
- client.DefaultRequestHeaders.Add(header.Key, header.Value);
- }
- using (HttpContent httpContent = new StringContent(postData, 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;
- }
- try
- {
- byte[] resultBytes = client.GetByteArrayAsync(url).Result;
- return Encoding.UTF8.GetString(resultBytes);
- }
- catch
- {
- return string.Empty;
- }
- }
- public static string HttpPost(string url, string postData, Dictionary<string, string>? headers = null, string contentType = "", int timeout = 0, Encoding? encoding = null)
- {
- HttpClient client = new HttpClient();
- if (headers != null)
- {
- foreach (var header in headers)
- {
- client.DefaultRequestHeaders.Add(header.Key, header.Value);
- }
- HttpResponseMessage response = client.GetAsync(url).Result;
- return response.Content.ReadAsStringAsync().Result;
- }
- }
- HttpContent content = new StringContent(postData ?? "", encoding ?? Encoding.UTF8);
- if (!string.IsNullOrWhiteSpace(contentType))
- {
- content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
- }
- try
- {
- using HttpResponseMessage responseMessage = client.PostAsync(url, content).Result;
- byte[] resultBytes = responseMessage.Content.ReadAsByteArrayAsync().Result;
- return Encoding.UTF8.GetString(resultBytes);
- }
- catch
- {
- return string.Empty;
- }
- }
- }
- }
|