c# HttpClient 上传文件并带参

public class Class1
     {
         private readonly string url = "https://*****";
         private readonly string file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "lepUrla.jpg");//文件
         public void Test()
         {
             string result = PostFileAsync(url, file).Result;
             Console.WriteLine(result);
         }

        private async Task<string> PostFileAsync(string url, string file, int timeout = 180000, Encoding encoding = null, Dictionary<string, string> header = null)
         {
             Dictionary<string, string> bodys = new Dictionary<string, string>
             {
                 { "img_md5", "c12e2b751d238953d91feb0a9811479e" }, //参数1
                 { "merchant_no", "0000" },     //参数2
             };

            HttpClientHandler handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate };
             handler.AllowAutoRedirect = true;
             handler.UseCookies = true;
             handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
             ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };//解决https终止问题
             HttpClient httpClient = new HttpClient(handler);
             httpClient.DefaultRequestHeaders.Connection.Add("keep-alive");
             httpClient.Timeout = TimeSpan.FromMilliseconds(timeout);
             if (header != null)
             {
                 foreach (KeyValuePair<string, string> item in header)
                 {
                     httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
                 }
             }


             using (MultipartFormDataContent content = new MultipartFormDataContent())
             {
                 content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(file)), "media", new FileInfo(file).Name);
                 if (bodys != null)
                 {
                     foreach (KeyValuePair<string, string> item in bodys)
                     {
                         //添加字符串参数,参数名为Key
                         content.Add(new StringContent(item.Value), item.Key);
                     }
                 }

                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url)
                 {
                     Content = content
                 };

                HttpCompletionOption option = HttpCompletionOption.ResponseContentRead | HttpCompletionOption.ResponseHeadersRead;//解决:将内容复制到流时出错
                 HttpResponseMessage response = httpClient.SendAsync(request, option).Result;
                 return await response.Content.ReadAsStringAsync();

            }


         }

    }

posted @ 2021-07-26 10:26  94cool  阅读(866)  评论(0)    收藏  举报