| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279 |
- using System;
- using System.Collections.Generic;
- using System.Net.Http;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using Newtonsoft.Json;
- public class HttpClientHelper
- {
- // 单例实例
- private static readonly Lazy<HttpClientHelper> _instance = new Lazy<HttpClientHelper>(() => new HttpClientHelper());
- // 全局访问属性
- public static HttpClientHelper Instance => _instance.Value;
- // 内部使用的 HttpClient
- private readonly HttpClient _httpClient;
- // 私有构造函数,防止外部实例化
- private HttpClientHelper()
- {
- _httpClient = new HttpClient();
- }
- // 定义内容类型枚举
- public enum ContentType
- {
- Json,
- FormData,
- Text,
- Xml,
- Plain,
- x_www_form
- }
- public void SetBaseAddress(string baseAddress)
- {
- _httpClient.BaseAddress = new Uri(baseAddress);
- }
- // 发送请求的方法(保持原有逻辑不变)
- public async Task<ApiResponse<string>> SendRequestAsync(
- HttpMethod method,
- string requestUri,
- object body = null,
- Dictionary<string, string> headers = null,
- ContentType contentType = ContentType.Json)
- {
- var request = new HttpRequestMessage
- {
- Method = method,
- RequestUri = new Uri(_httpClient.BaseAddress, requestUri)
- };
- if (headers != null)
- {
- foreach (var header in headers)
- {
- request.Headers.Add(header.Key, header.Value);
- }
- }
- if (body != null)
- {
- switch (contentType)
- {
- case ContentType.Json:
- request.Content = new StringContent(
- body.ToString(),
- Encoding.UTF8,
- "application/json");
- break;
- case ContentType.FormData:
- if (body is Dictionary<string, string> formData)
- {
- var multipartContent = new MultipartFormDataContent();
- foreach (var pair in formData)
- {
- multipartContent.Add(new StringContent(pair.Value, Encoding.UTF8),
- $"\"{pair.Key}\""); // 注意 Key 要加引号
- }
- request.Content = multipartContent;
- }
- else
- {
- return ApiResponse<string>.Failure("FormData body must be Dictionary<string, string>", 400);
- }
- break;
- case ContentType.Text:
- request.Content = new StringContent(
- body.ToString(),
- Encoding.UTF8,
- "text/plain");
- break;
- case ContentType.Xml:
- request.Content = new StringContent(
- body.ToString(),
- Encoding.UTF8,
- "application/xml");
- break;
- case ContentType.Plain:
- request.Content = new StringContent(
- body.ToString(),
- Encoding.UTF8,
- "text/plain");
- break;
- case ContentType.x_www_form:
- if (body is Dictionary<string, string> xformData)
- {
- var formContent = new FormUrlEncodedContent(xformData);
- request.Content = formContent;
- }
- else
- {
- return ApiResponse<string>.Failure("FormData body must be Dictionary<string, string>", 400);
- }
- break;
- default:
- return ApiResponse<string>.Failure("Unsupported content type", 400);
- }
- }
- HttpResponseMessage response;
- try
- {
- response = await _httpClient.SendAsync(request);
- }
- catch (Exception ex)
- {
- return ApiResponse<string>.Failure($"Network error: {ex.Message}", 503);
- }
- var responseBody = await response.Content.ReadAsStringAsync();
- if (response.IsSuccessStatusCode)
- {
- return ApiResponse<string>.Success(responseBody, (int)response.StatusCode);
- }
- else
- {
- return ApiResponse<string>.Failure(responseBody, (int)response.StatusCode);
- }
- }
- public ApiResponse<string> SendRequest(
- HttpMethod method,
- string requestUri,
- object body = null,
- Dictionary<string, string> headers = null,
- ContentType contentType = ContentType.Json)
- {
- var request = new HttpRequestMessage
- {
- Method = method,
- RequestUri = new Uri(_httpClient.BaseAddress, requestUri)
- };
- if (headers != null)
- {
- foreach (var header in headers)
- {
- request.Headers.Add(header.Key, header.Value);
- }
- }
- if (body != null)
- {
- switch (contentType)
- {
- case ContentType.Json:
- request.Content = new StringContent(
- body.ToString(),
- Encoding.UTF8,
- "application/json");
- break;
- case ContentType.FormData:
- if (body is Dictionary<string, string> formData)
- {
- var multipartContent = new MultipartFormDataContent();
- foreach (var pair in formData)
- {
- multipartContent.Add(
- new StringContent(pair.Value, Encoding.UTF8),
- $"\"{pair.Key}\""); // 注意 key 加引号
- }
- request.Content = multipartContent;
- }
- else
- {
- return ApiResponse<string>.Failure("FormData body must be Dictionary<string, string>", 400);
- }
- break;
- case ContentType.x_www_form:
- if (body is Dictionary<string, string> xformData)
- {
- request.Content = new FormUrlEncodedContent(xformData);
- }
- else
- {
- return ApiResponse<string>.Failure("FormData body must be Dictionary<string, string>", 400);
- }
- break;
- case ContentType.Text:
- case ContentType.Plain:
- request.Content = new StringContent(
- body.ToString(),
- Encoding.UTF8,
- "text/plain");
- break;
- case ContentType.Xml:
- request.Content = new StringContent(
- body.ToString(),
- Encoding.UTF8,
- "application/xml");
- break;
- default:
- return ApiResponse<string>.Failure("Unsupported content type", 400);
- }
- }
- HttpResponseMessage response;
- try
- {
- // ✅ 使用 SendAsync().Result 模拟同步发送
- response = _httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead).Result;
- }
- catch (Exception ex)
- {
- return ApiResponse<string>.Failure($"Network error: {ex.Message}", 503);
- }
- var responseBody = response.Content.ReadAsStringAsync().Result;
- if (response.IsSuccessStatusCode)
- {
- return ApiResponse<string>.Success(responseBody, (int)response.StatusCode);
- }
- else
- {
- return ApiResponse<string>.Failure(responseBody, (int)response.StatusCode);
- }
- }
- public class ApiResponse<T>
- {
- public bool IsSuccess { get; set; }
- public int StatusCode { get; set; }
- public string ErrorMessage { get; set; }
- public T Result { get; set; }
- public static ApiResponse<T> Success(T result, int statusCode)
- {
- return new ApiResponse<T> { IsSuccess = true, StatusCode = statusCode, Result = result };
- }
- public static ApiResponse<T> Failure(string message, int statusCode)
- {
- return new ApiResponse<T> { IsSuccess = false, StatusCode = statusCode, ErrorMessage = message };
- }
- }
- }
|