• HttpClient封装方法


    //post请求
            public static string PostRequest(string url, HttpContent data)
            {
                var handler = new HttpClientHandler() { UseCookies = false };
                HttpClient client = new HttpClient(handler);
                var message = new HttpRequestMessage(HttpMethod.Post, url);
                message.Content = data;
                //message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", GetRemoteToken());
                var response = client.SendAsync(message).Result;
                response.EnsureSuccessStatusCode();
                var result = response.Content.ReadAsStringAsync().Result;
                return result;
            }
    
    
     //发送文件
            public static void SendFile(string url,string path = @"C:<filepath>	est.txt")
            {
                using (var client = new HttpClient())
                using (var content = new MultipartFormDataContent())
                {
                    client.BaseAddress = new Uri("http://localhost");
    
                    var fileContent1 = new ByteArrayContent(File.ReadAllBytes(path));
                    fileContent1.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = Path.GetFileName(path)
                    };
                    content.Add(fileContent1);
    
                    var result = client.PostAsync(url, content).Result;
                }
            }
        /// <summary>
        /// Http请求帮助类
        /// </summary>
        public class HttpHelper
        {
            /// <summary>
            /// 同步GET请求
            /// </summary>
            /// <param name="url"></param>
            /// <param name="headers"></param>
            /// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param>
            /// <returns></returns>
            public static string HttpGet(string url, Dictionary<string, string> headers = null, int timeout = 0)
            {
                using (HttpClient client = new HttpClient())
                {
                    if (headers != null)
                    {
                        foreach (KeyValuePair<string, string> header in headers)
                        {
                            client.DefaultRequestHeaders.Add(header.Key, header.Value);
                        }
                    }
                    if (timeout > 0)
                    {
                        client.Timeout = new TimeSpan(0, 0, timeout);
                    }
                    Byte[] resultBytes = client.GetByteArrayAsync(url).Result;
                    return Encoding.UTF8.GetString(resultBytes);
                }
            }
            /// <summary>
            /// 异步GET请求
            /// </summary>
            /// <param name="url"></param>
            /// <param name="headers"></param>
            /// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param>
            /// <returns></returns>
            public static async Task<string> HttpGetAsync(string url, Dictionary<string, string> headers = null, int timeout = 0)
            {
                using (HttpClient client = new HttpClient())
                {
                    if (headers != null)
                    {
                        foreach (KeyValuePair<string, string> header in headers)
                        {
                            client.DefaultRequestHeaders.Add(header.Key, header.Value);
                        }
                    }
                    if (timeout > 0)
                    {
                        client.Timeout = new TimeSpan(0, 0, timeout);
                    }
                    Byte[] resultBytes = await client.GetByteArrayAsync(url);
                    return Encoding.Default.GetString(resultBytes);
                }
            }
    
    
            /// <summary>
            /// 同步POST请求
            /// </summary>
            /// <param name="url"></param>
            /// <param name="postData"></param>
            /// <param name="headers"></param>
            /// <param name="contentType"></param>
            /// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param>
            /// <param name="encoding">默认UTF8</param>
            /// <returns></returns>
            public static string HttpPost(string url, string postData, Dictionary<string, string> headers = null, string contentType = null, int timeout = 0, Encoding encoding = null)
            {
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36");
                    if (headers != null)
                    {
                        foreach (KeyValuePair<string, string> header in headers)
                        {
                            client.DefaultRequestHeaders.Add(header.Key, header.Value);
                        }
                    }
                    if (timeout > 0)
                    {
                        client.Timeout = new TimeSpan(0, 0, timeout);
                    }
                    using (HttpContent content = new StringContent(postData ?? "", encoding ?? Encoding.UTF8))
                    {
                        if (contentType != null)
                        {
                            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
                        }
                        using (HttpResponseMessage responseMessage = client.PostAsync(url, content).Result)
                        {
                            Byte[] resultBytes = responseMessage.Content.ReadAsByteArrayAsync().Result;
                            return Encoding.UTF8.GetString(resultBytes);
                        }
                    }
                }
            }
    
            /// <summary>
            /// 异步POST请求
            /// </summary>
            /// <param name="url"></param>
            /// <param name="postData"></param>
            /// <param name="headers"></param>
            /// <param name="contentType"></param>
            /// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param>
            /// <param name="encoding">默认UTF8</param>
            /// <returns></returns>
            public static async Task<string> HttpPostAsync(string url, string postData, Dictionary<string, string> headers = null, string contentType = null, int timeout = 0, Encoding encoding = null)
            {
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36");
                    if (headers != null)
                    {
                        foreach (KeyValuePair<string, string> header in headers)
                        {
                            client.DefaultRequestHeaders.Add(header.Key, header.Value);
                        }
                    }
                    if (timeout > 0)
                    {
                        client.Timeout = new TimeSpan(0, 0, timeout);
                    }
                    using (HttpContent content = new StringContent(postData ?? "", encoding ?? Encoding.UTF8))
                    {
                        if (contentType != null)
                        {
                            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
                        }
                        using (HttpResponseMessage responseMessage = await client.PostAsync(url, content))
                        {
                            Byte[] resultBytes = await responseMessage.Content.ReadAsByteArrayAsync();
                            return Encoding.UTF8.GetString(resultBytes);
                        }
                    }
                }
            }
        }
    
    
    

      

     
       //httpcontent类型
           //json
                HttpContent content1 = new StringContent("{a:1,b:2}", Encoding.UTF8, "application/json");
           //from
                HttpContent content2 = new FormUrlEncodedContent(new Dictionary<string, string>()
               {
                  {"email", "1"},
                  {"pwd","11"}
               });
    

      

  • 相关阅读:
    TMD 这个写笔记的号,盗了有意思吗
    类成员的指针必须NULL化,否则是乱七八糟的东西
    超前引用不可使用类名来定义变量和函数的变量参数,只可用来定义引用或者指针。
    XP下,移动窗口产生重影的问题
    生成ico格式图标
    设置窗口的z-order总是在最底部
    关于windows的锁定状态
    使用Layered Window遇到的一些问题及解决方法
    转-使用wifi调试程序
    URL的格式
  • 原文地址:https://www.cnblogs.com/xxxin/p/9367469.html
Copyright © 2020-2023  润新知