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);
            }
        }
  • 相关阅读:
    软件设计7个原则
    vue.js 样式绑定 font-size 问题
    实例理解scala 隐式转换(隐式值,隐式方法,隐式类)
    著名端口整理(常用服务的默认端总结)
    .NET Core Web API 实现大文件分片上传
    ngnix反向代理tomcat,ssl证书配置及自定义错误页面
    微信登录闪退
    gradle如何配置阿里云的中央仓库
    HashMap底层实现和原理
    关于Java中String类的hashCode方法
  • 原文地址:https://www.cnblogs.com/njl041x/p/13051293.html
Copyright © 2011-2022 走看看