C#操作HttpClient工具类库

640?wx_fmt=jpeg

using System;

using System.Collections.Generic;

using System.Net.Http;


using System.Windows.Forms;


using System.Configuration;

using System.IO;

using Newtonsoft.Json;


namespace Dcflow

{

    public class HttpHelper

    {

        //获取Configuration对象

        

        public static string DCFLOW_ZUUL = ConfigurationManager.AppSettings["SERVER_URL"];


        //token键

        public static string ACCESS_TOKEN_KEY = "";

        //token值

        public static string ACCESS_TOKEN_VALUE = "";


        private static Dictionary<string, string> headers;


        public static Dictionary<string, string> Headers { get => headers; set => headers = value; }


        private static readonly HttpClient _httpClient;


        static HttpHelper()

        {

            try

            {

                //HttpClient热身

                _httpClient = new HttpClient() { BaseAddress = new Uri(DCFLOW_ZUUL) };

                _httpClient.DefaultRequestHeaders.Connection.Add("keep-alive");

                _httpClient.SendAsync(new HttpRequestMessage

                {

                    Method = new HttpMethod("HEAD"),

                    RequestUri = new Uri(DCFLOW_ZUUL + "/")

                }).Result.EnsureSuccessStatusCode();

            }

            catch (Exception)

            {

                

            }

        }


        public static String httpGet(string url)

        {

            

            if (HttpHelper.headers != null)

            {

                _httpClient.DefaultRequestHeaders.Clear();

                headers[ACCESS_TOKEN_KEY] = HttpHelper.ACCESS_TOKEN_VALUE;

                

                // 设置请求头

                foreach (KeyValuePair<string, string> item in headers)

                {


                    _httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);


                }

            }


            var data = "";

            try

            {

                // response

                var response = _httpClient.GetAsync(new Uri(DCFLOW_ZUUL + url)).Result;

                data = response.Content.ReadAsStringAsync().Result;


            }

            catch (Exception e)

            {

                MessageBox.Show("HTTP GET请求失败,请检查网络或联系管理员查看服务器状态,错误消息:" + e.Message);

                //throw;

            }

            return data;//接口调用成功获取的数据

        }


        public static String httpPost(string url, Dictionary<string, string> param, string dataType)

        {

            

            if (HttpHelper.headers != null)

            {

                _httpClient.DefaultRequestHeaders.Clear();

                headers[ACCESS_TOKEN_KEY] = HttpHelper.ACCESS_TOKEN_VALUE;


                //设置请求头

                foreach (KeyValuePair<string, string> item in headers)

                {

                    _httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);

                }

            }


            var data = "";

            try

            {

                ByteArrayContent content = null;

                if (dataType.ToLower().Equals("json"))

                {

                    content = new StringContent(JsonConvert.SerializeObject(param));

                    //设置Http的内容标头

                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

                }

                else

                {

                    content = new FormUrlEncodedContent(param);

                }


                // response

                var response = _httpClient.PostAsync(DCFLOW_ZUUL + url, content).Result;

                data = response.Content.ReadAsStringAsync().Result;


            }

            catch (Exception e)

            {

                MessageBox.Show("HTTP POST请求失败,请检查网络或联系管理员查看服务器状态,错误消息:" + e.Message);

                //throw;

            }



            return data;//接口调用成功数据

        }


        public static String httpUploadAsync(string url, List<string> filePath)

        {

            var data = "";

            

  

            try

            {

                using (var content = new MultipartFormDataContent())

                {

                    for (int i = 0; i < filePath.Count; i++)

                    {

                        FileStream fs = File.OpenRead(filePath[i]);

                        var streamContent = new StreamContent(fs);


                        var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);


                        content.Add(imageContent, "upfile", Path.GetFileName(filePath[i]));

                        fs.Close();

                    }


                    // response

                    var response = _httpClient.PostAsync(DCFLOW_ZUUL + url, content).Result;

                    data = response.Content.ReadAsStringAsync().Result;

                };

            }

            catch (Exception e)

            {

                MessageBox.Show("HTTP POST MultipartFormData 请求失败,请检查网络或联系管理员查看服务器状态,错误消息:" + e.Message);

                //throw;

            }

            

            return data;

        }


    }

}


猜你喜欢

转载自blog.csdn.net/xishining/article/details/86770196