using System.Net.Http.Headers; using System.Text; using EFCoreDatabase.Entities; namespace NewWMSProject.Services; public interface IHttpClientService { public Task PostAsyncJson(string json, string apiAddress); } public class HttpClientService:IHttpClientService { /// /// 使用post方法异步请求WebAPI /// /// 发送的参数字符串,只能用json /// /// < returns > 返回的字符串 public async Task PostAsyncJson(string json, string apiAddress) { var responseBody = string.Empty; bool test0Prd1Flag = true; //保证接口处于测试服务状态下 //WebAPI接口地址 string url = apiAddress; using (HttpClient client = new HttpClient()) { HttpContent content = new StringContent(json); //设置传输数据类型为json content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); client.Timeout = new TimeSpan(1, 0, 0, 0, 0); client.DefaultRequestHeaders.Add("Connection", "Keep-Alive"); client.DefaultRequestHeaders.Add("Keep-Alive", "timeout=600"); client.DefaultRequestHeaders.Add("ContentType", "application/json"); client.DefaultRequestHeaders.Add("Accept", "*/*"); //设置用户名密码 //AuthenticationHeaderValue authentication = new AuthenticationHeaderValue("Basic", // Convert.ToBase64String(Encoding.UTF8.GetBytes(test0Prd1Flag ? $"{HANDApiUsernameTest}:{HANDApiPasswordTest}" : $"{HANDApiUsername}:{HANDApiPassword}"))); //client.DefaultRequestHeaders.Authorization = authentication; HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { response.EnsureSuccessStatusCode(); responseBody = await response.Content.ReadAsStringAsync(); } } return responseBody; } }