C# HttpClientHelper

    public class HttpClientHelper
    {
        // 执行post操作
        public static string doPost(string url, Dictionary<string, string> parameters, int timeOutInMillisecond)
        {
            using (HttpClient client = new HttpClient())
            {
                HttpContent content = new MyFormUrlEncodedContent(parameters);
                Task<HttpResponseMessage> task = client.PostAsync(url, content);
                if (task.Wait(timeOutInMillisecond))
                {
                    HttpResponseMessage response = task.Result;
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        Task<string> result = response.Content.ReadAsStringAsync();
                        result.Wait();
                        return result.Result;
                    }
                }
            }
            return null;
        }

        public static string doPostJson(string url, string jsonData, string cookieValue, int timeOutInMillisecond)
        {
            try
            {
                HttpClientHandler handler = new HttpClientHandler() { UseCookies = false };//手动headers添加cookies.
                using (HttpClient client = new HttpClient(handler))
                {
                    HttpContent requestContent = new StringContent(jsonData);
                    requestContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    if (!string.IsNullOrEmpty(cookieValue))
                    {
                        requestContent.Headers.Add("Cookie", cookieValue);
                    }
                    Task<HttpResponseMessage> task = client.PostAsync(url, requestContent);

                    #region 构建请求方式2
                    //HttpRequestMessage requestMessage = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, requestUrl);
                    //requestMessage.Content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                    //if (!string.IsNullOrEmpty(cookieValue))
                    //{
                    //    requestMessage.Headers.Add("Cookie", cookieValue);
                    //}
                    //Task<HttpResponseMessage> task = client.SendAsync(requestMessage);
                    #endregion

                    if (task.Wait(timeOutInMillisecond))
                    {
                        HttpResponseMessage response = task.Result;
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            Task<string> result = response.Content.ReadAsStringAsync();
                            result.Wait();
                            string content = result.Result;
                            LogUtil.Logger.Debug("Debug:HttpClientHelper.doPostJson请求结果:" + content);
                            return content;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.Logger.Error(string.Format("Error:HttpClientHelper.doPostJson-------->error:{0}", ex.Message));
            }
            return "";
        }


    }

    /// <summary>
    /// 默认的FormUrlEncodedContent碰到超长的文本会出现uri too long的异常,这里自己封装一个
    /// 参考来自 stackoverflow
    /// </summary>
    public class MyFormUrlEncodedContent : ByteArrayContent
    {
        public MyFormUrlEncodedContent(IEnumerable<KeyValuePair<string, string>> nameValueCollection)
            : base(MyFormUrlEncodedContent.GetContentByteArray(nameValueCollection))
        {
            base.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
        }
        private static byte[] GetContentByteArray(IEnumerable<KeyValuePair<string, string>> nameValueCollection)
        {
            StringBuilder stringBuilder = new StringBuilder();
            foreach (KeyValuePair<string, string> current in nameValueCollection)
            {
                if (stringBuilder.Length > 0)
                {
                    stringBuilder.Append('&');
                }

                stringBuilder.Append(MyFormUrlEncodedContent.Encode(current.Key));
                stringBuilder.Append('=');
                stringBuilder.Append(MyFormUrlEncodedContent.Encode(current.Value));
            }
            return Encoding.Default.GetBytes(stringBuilder.ToString());
        }

        private static string Encode(string data)
        {
            if (string.IsNullOrEmpty(data))
            {
                return string.Empty;
            }
            return WebUtility.UrlEncode(data);
        }
    }

 

posted @ 2020-06-05 18:22  i迷倪  阅读(1152)  评论(0编辑  收藏  举报