当前位置: 首页 > 工具软件 > httphelper > 使用案例 >

HttpHelper代码(C#)

荀裕
2023-12-01
public static class HttpHelper
    {
        /// <summary>  
        /// 获取文件集合对应的ByteArrayContent集合  
        /// </summary>  
        /// <param name="files"></param>  
        /// <returns></returns>  
        private static List<ByteArrayContent> GetFileByteArrayContent(HashSet<string> files)
        {
            List<ByteArrayContent> list = new List<ByteArrayContent>();
            foreach (var file in files)
            {
                var fileContent = new ByteArrayContent(File.ReadAllBytes(file));
                fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = Path.GetFileName(file)
                };
                list.Add(fileContent);
            }
            return list;
        }
        /// <summary>  
        /// 获取键值集合对应的ByteArrayContent集合  
        /// </summary>  
        /// <param name="collection"></param>  
        /// <returns></returns>  
        private static List<ByteArrayContent> GetFormDataByteArrayContent(NameValueCollection collection)
        {
            List<ByteArrayContent> list = new List<ByteArrayContent>();
            foreach (var key in collection.AllKeys)
            {
                var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(collection[key]));
                dataContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                {
                    Name = key
                };
                list.Add(dataContent);
            }
            return list;
        }

        public static string PostFormData(string url, NameValueCollection collection)
        {          
            using (HttpClient client = new HttpClient())
            {
                string result_info = "";
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/json"));//设定要响应的数据格式  
                using (var content = new MultipartFormDataContent())//表明是通过multipart/form-data的方式上传数据  
                {
                    var formDatas = GetFormDataByteArrayContent(collection);//获取键值集合对应的ByteArrayContent集合  
                   
                    Action<List<ByteArrayContent>> act = (dataContents) =>
                    {
                        //声明一个委托,该委托的作用就是将ByteArrayContent集合加入到MultipartFormDataContent中  
                        foreach (var byteArrayContent in dataContents)
                        {
                            content.Add(byteArrayContent);
                        }
                    };
                    act(formDatas);//执行act  

                    try
                    {
                        var result = client.PostAsync(url, content).Result;//post请求  
                        //确保HTTP成功状态值
                        result.EnsureSuccessStatusCode();
                        result_info = result.Content.ReadAsStringAsync().Result;//将响应结果显示在文本框内  
                    }
                    catch(Exception ex)
                    {
                        Common.WriteTextLog("http响应错误", ex.ToString(), DateTime.Now);
                    }
                }
                return result_info;
            }  
        }

        public static string PostFormFile(string url, HashSet<string> files_hash)
        {
            using (HttpClient client = new HttpClient())
            {
                string result_info = "";
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/json"));//设定要响应的数据格式  
                using (var content = new MultipartFormDataContent())//表明是通过multipart/form-data的方式上传数据  
                {

                    var files = GetFileByteArrayContent(files_hash);//获取文件集合对应的ByteArrayContent集合  
                    Action<List<ByteArrayContent>> act = (dataContents) =>
                    {//声明一个委托,该委托的作用就是将ByteArrayContent集合加入到MultipartFormDataContent中  
                        foreach (var byteArrayContent in dataContents)
                        {
                            content.Add(byteArrayContent);
                        }
                    };
                    act(files);//执行act  

                    try
                    {
                        var result = client.PostAsync(url, content).Result;//post请求  
                        //确保HTTP成功状态值
                        result.EnsureSuccessStatusCode();
                        result_info = result.Content.ReadAsStringAsync().Result;//将响应结果显示在文本框内  
                    }
                    catch (Exception ex)
                    {
                        Common.WriteTextLog("http响应错误", ex.ToString(), DateTime.Now);
                    } 
                }
                return result_info;
            }
        }

        public static string PostFormUrl(string url, Dictionary<string, string> key_value_set)
        {
            using (var client = new HttpClient())
            {
                string result_info = "";
                //使用FormUrlEncodedContent做HttpContent
                var content = new FormUrlEncodedContent(key_value_set);

                try
                {
                    var result = client.PostAsync(url, content).Result;//post请求  
                    //确保HTTP成功状态值
                    result.EnsureSuccessStatusCode();
                    result_info = result.Content.ReadAsStringAsync().Result;//将响应结果显示在文本框内  
                }
                catch (Exception ex)
                {
                    Common.WriteTextLog("http响应错误", ex.ToString(), DateTime.Now);
                }
                return result_info;
            }
        }
        
    }

 类似资料: