C# HttpClient 的那些坑

时间:2021-09-17
本文章向大家介绍C# HttpClient 的那些坑,主要包括C# HttpClient 的那些坑使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
点击查看代码
  /// 
        /// HttpPost
        /// 
        /// 非【application/json】 建议使用 Method HttpPost 使用此方法可能会字符超长导致请求400
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static string HttpClientPost(string url, string requestJson, Dictionary headers = null,string contentType= "application/json")
        {
            try
            {
                string result = string.Empty;
                Uri postUrl = new Uri(url);
                using (var httpClient = new HttpClient())
                {
                    if (headers != null)
                    {
                        foreach (var header in headers)
                            httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                    using (HttpContent httpContent = new StringContent(requestJson))
                    {
                        if (headers != null)
                        {
                            foreach (var header in headers)
                                httpContent.Headers.Add(header.Key, header.Value);
                        }
                        httpContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);


                        httpClient.Timeout = new TimeSpan(0, 0, 60);
                        result = httpClient.PostAsync(url, httpContent).Result.Content.ReadAsStringAsync().Result;

                    }

                }
                return result;
            }
            catch (Exception e)
            {
                throw e;
            }
        }

调用方式:

// model 为json对象
HttpClientPost("url",JsonConvert.SerializeObject(model))

当使用【ContentType】为【application/json】的时候,上述方法一点问题没有,参数长度也没有限制,然而使用【application/x-www-form-urlencoded】或使用【form-data】时,参数有了限制,长度和get请求的限制一致,而使用此方法请求,依然可以收到返回值,只不过返回值为空,响应抛出【400-bad request】的错误代码,就很迷惑。。。 然后调整成下列方法后,问题就其妙的解决了。

点击查看代码


        /// 
        /// 发起POST同步请求(Key Value)
        /// Method【application/json】【application/x-www-form-urlencoded】
        /// 参数超长时使用此方法
        /// 
        /// 
        /// 
        /// 
        /// 
        public static string HttpPost(string baseAddr, string path, FormUrlEncodedContent content,Dictionary header=null, string contentType ="")
        {
            try
            {
                string resultContent = string.Empty;
                using (HttpClient client = new HttpClient())
                {
//                    client.BaseAddress = new Uri(baseAddr);

                    // header 
                    if (header != null)
                        foreach (var item in header)
                        {
                            content.Headers.Add(item.Key, item.Value);
                        }

                    if (!string.IsNullOrEmpty(contentType))
                    {
                        content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                    }
                    HttpResponseMessage response = client.PostAsync(baseAddr+path, content).Result;
                    resultContent = response.Content.ReadAsStringAsync().Result;
                }
                return resultContent;
            }
            catch (Exception)
            {

                throw;
            }
            
        }

使用方式:

点击查看代码
  var content = new FormUrlEncodedContent(new[] {
    // body 为请求接口的参数名称,依据个人实际需求调整;参数依然为json对象
                new KeyValuePair("body", JsonConvert.SerializeObject(model))
            });

HttpPost("url", "可移除", content, _header, "application/x-www-form-urlencoded")

这个时候,接口就可以使用了,并且上面这个方法可以在类型(contentType)中使用,不会出现参数超长及其他问题,唯一美中不足的是,参数格式化这块没有第一个方法简单。

这个问题困扰了一天的时间,特此记录下,表示我现在忐忑的心情。。

本文来自博客园,作者:ThinkWsir,转载请注明原文链接:https://www.cnblogs.com/thinkw/p/15304712.html

原文地址:https://www.cnblogs.com/thinkw/p/15304712.html