private async Task <string> HttpRequest(Uri baseAddress, Dictionary <string, string> heads = null, bool isGzip = false, HttpMethod method = null, object formData = null, string acceptMediaType = "*/*", string mediaType = "application/json", string charset = "UTF-8", Dictionary <string, string> acceptMediaTypes = null ) { if (!MediaType.IsNullOrEmpty()) // 如果 MediaType 不为空, 说明用户设置了全局 MediaType { if (mediaType == "application/json") // 如果 MediaType 和默认值不同, 说明用户设置了 MediaType { mediaType = MediaType; } } if (method == null) { method = HttpMethod.Get; } using (var handler = new HttpClientHandler { UseCookies = false }) using (var client = new System.Net.Http.HttpClient(handler) { BaseAddress = baseAddress }) { var message = new HttpRequestMessage(method, baseAddress.PathAndQuery); var encoding = Encoding.GetEncoding(charset); if (method == HttpMethod.Post) { StringContent content; if (formData == null) { content = new StringContent(string.Empty, encoding, mediaType); message.Content = content; } else { if (formData is string) { content = new StringContent(formData as string, encoding, mediaType); } else { if (mediaType == "application/x-www-form-urlencoded") { content = new StringContent(string.Join("&", formData.ToDictionary().Select(m => m.Key + "=" + m.Value)), encoding, mediaType); } else { content = new StringContent(formData.ToJson(), encoding, mediaType); } } message.Content = content; } // message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptMediaType)); if (acceptMediaTypes != null) { foreach (var mediaTypeItem in acceptMediaTypes) { if (!mediaTypeItem.Value.IsNullOrEmpty()) { message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(mediaTypeItem.Key, Convert.ToDouble(mediaTypeItem.Value))); } else { message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(mediaTypeItem.Key)); } } } } if (heads != null) { foreach (var head in heads) { message.Headers.Add(head.Key, head.Value); } } message.Headers.Add("Cookie", GetCookie()); var result = client.SendAsync(message).Result; result.EnsureSuccessStatusCode(); if (result.Headers.TryGetValues("Set-Cookie", out var cookie)) { cookie.ToList().ForEach(m => SetCookie(m)); } string httpContent; if (isGzip) { httpContent = StringExtension.GZipDecompress(await result.Content.ReadAsByteArrayAsync()); } else { httpContent = await result.Content.ReadAsStringAsync(); } return(httpContent); } }