zoukankan      html  css  js  c++  java
  • 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);
            }
        }
  • 相关阅读:
    python测试开发django-115.Paginator分页器展示table表格数据
    python面试题-如"上海 深圳 深圳 上海",要求输入一个匹配模式,比如: aabb,判断是否符合
    python测试开发django-114.ModelForm中局部钩子(clean_)和全局钩子校验
    python测试开发django-113.使用Bootstrap框架
    MySQL将查询的结果作为update更新的数据,且在原字段数据后 CONCAT拼接(lej)
    MongoDB和Redis的区别是什么
    【精选】由浅入深带你吃透MQ原理与应用场景
    mysql 往表中某个字段的字符串后追加字符串
    mongodb 安装及使用
    Redis和MongoDB的区别(面试受用)
  • 原文地址:https://www.cnblogs.com/njl041x/p/13051293.html
Copyright © 2011-2022 走看看