HttpHelper代碼(C#)

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;
            }
        }
        
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章