HttpClient扩展类

注册HttpClient

private static HttpClient _httpClient;
        public string host = JSONHelper.ReadJSON<string>("ServerUrl").ToString();
        public RemoteHttpClient()
        {
            var handler = new HttpClientHandler();
            handler.ServerCertificateCustomValidationCallback +=
                (sender, cert, chain, sslPolicyErrors) => true;
            _httpClient = new HttpClient(handler);
        }

获取接口列表

 public T Getlist<T>(string productlist)
        {
            var url = new Uri(new Uri(host), $"/api/{productlist}/1/1000");
            var httpRequest = new HttpRequestMessage();
            httpRequest.Method = HttpMethod.Get;
            httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", JSONHelper.ReadJSON<string>("accessToken").ToString());
            httpRequest.RequestUri = url;
            var httpResponseMessage = _httpClient.SendAsync(httpRequest).Result;
            var bodyJson = httpResponseMessage.Content.ReadAsStringAsync().Result;
            var body = JObject.Parse(bodyJson);
            int Code = Convert.ToInt32(body["statusCode"]?.ToString());
            if (!Code.Equals(200))
            {
                string mess = body["errors"]?.ToString();
                AlertForm.ShowAlert(mess, AlertType.Error);
                return default;
            }
            var data = body["data"].ToString();
            return JsonConvert.DeserializeObject<T>(data);
        }

form请求

 /// <summary>
        /// 添加多个文件
        /// </summary>
        /// <param name="addProduct"></param>
        /// <returns></returns>
        public bool FromSave(_AddProductDto data)
        {
            try
            {
                var postContent = new MultipartFormDataContent();
                string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x"));
                postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}");
                var url = new Uri(new Uri(host), "/api/product/for-qtx");
                for (int i = 0; i < data.files.Count; i++)
                {
                    string qtxname = $"{i}tsl.qtx";
                    var stream = new FileStream(data.files[i], FileMode.OpenOrCreate);
                    //files为文件key, files[0].FileName 为文件名称
                    postContent.Add(new StreamContent(stream, (int)stream.Length), "files", qtxname);
                }
                Dictionary<string, KeyValuePair<string, byte[]>> param = new Dictionary<string, KeyValuePair<string, byte[]>>();
                //Region为请求文件接口需要的参数,根据调用接口参数而定
                var jsontag = JsonConvert.SerializeObject(data.tagIds);
                var fabricTypeId = JsonConvert.SerializeObject(data.fabricTypeId);
                var productTypeId= JsonConvert.SerializeObject(data.productTypeId);
                var productCategoryId = JsonConvert.SerializeObject(data.productCategoryId);
                var productStatusId = JsonConvert.SerializeObject(data.productStatusId);
                postContent.Add(new StringContent(data.name), "name");
                postContent.Add(new StringContent(data.nameEn), "nameEn");
                postContent.Add(new StringContent(data.no), "no");
                postContent.Add(new StringContent(data.description), "description");
                postContent.Add(new StringContent(productCategoryId), "productCategoryId");
                postContent.Add(new StringContent( productStatusId), "productStatusId");
                postContent.Add(new StringContent( productTypeId), "productTypeId");
                postContent.Add(new StringContent( fabricTypeId), "fabricTypeId");
                postContent.Add(new StringContent(jsontag), "files");
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", JSONHelper.ReadJSON<string>				("accessToken").ToString());
                var response = _httpClient.PostAsync(url, postContent).Result;
                if (response.IsSuccessStatusCode)
                {
                    var responseStr = response.Content.ReadAsStringAsync();
                    return false;
                }
                return true;
            }
            catch (Exception)
            {

                throw;
            }
        }

单文件请求

 /// <summary>
        /// multipart/form-data请求
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool addfabric(addfabricDto data)
        {
            try
            {
                var postContent = new MultipartFormDataContent();
                string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x"));
                postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}");
                var url = new Uri(new Uri(host), "/api/fabric/for-qtx");
                if (!string.IsNullOrEmpty(data.file))
                {
                    var stream = new FileStream(data.file, FileMode.OpenOrCreate);
                    //files为文件key, files[0].FileName 为文件名称
                    postContent.Add(new StreamContent(stream, (int)stream.Length), "file", "Miss.qtx");
                    //Region为请求文件接口需要的参数,根据调用接口参数而定
                    postContent.Add(new StringContent(data.name), "name");
                    postContent.Add(new StringContent(data.nameEn), "nameEn");
                    postContent.Add(new StringContent(data.concentrationUnit), "concentrationUnit");
                    postContent.Add(new StringContent(data.sort.ToString()), "sort");
                }
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", JSONHelper.ReadJSON<string>("accessToken").ToString());
                var response = _httpClient.PostAsync(url, postContent).Result;
                if (response.IsSuccessStatusCode)
                {
                    var responseStr =  response.Content.ReadAsStringAsync();
                    return false;
                }
                return true;
            }
            catch (Exception)
            {
                
                throw;
            }
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值