/// <summary> /// 通过HttpPost提交数据 /// </summary> /// <param name="url">请求Url</param> /// <param name="data">提交字符数据</param> /// <param name="encoder">字符数据编码(默认为UTF-8)</param> /// <param name="mediaType">字符数据类型</param> /// <param name="queryDir">表单数据集合(Value可为有效的文件路径,否者均为文本text/text)</param> /// <param name="timeout">请求超时时间(单位:秒)</param> /// <param name="cookieContainer">Cookie容器</param> /// <returns></returns> public static Stream PostData(string url, string data = null, Encoding encoder = null, string mediaType = "text/text", Dictionary <string, string> queryDir = null, int timeout = 30, CookieContainer cookieContainer = null) { if (url.IsNullOrEmpty()) { throw new ArgumentNullException("url", "请求URL地址不能为空"); } HttpClient client; if (cookieContainer != null) { client = new HttpClient(new HttpClientHandler { CookieContainer = cookieContainer, UseCookies = true, }); } else { client = new HttpClient(); } client.Timeout = new TimeSpan(timeout * 1000 * 10000); HttpContent content = null; StringContent strContent = null; FormUrlEncodedContent formContent = null; MultipartFormDataContent multiContent = null; if (!data.IsNullOrEmpty()) { content = strContent = new StringContent(data, (encoder ?? Encoding.UTF8), mediaType); } if (queryDir != null) { var queries = queryDir.Select(d => new { d.Key, FileInfo = d.Value.GetFileInfo(), d.Value }).GroupBy(d => d.FileInfo?.Exists ?? false); if (queries.Where(d => d.Key).Count() == 0 && data.IsNullOrEmpty()) { content = formContent = new FormUrlEncodedContent(queryDir); } else { content = multiContent = new MultipartFormDataContent(); if (strContent != null) { multiContent.Add(strContent); } var texts = queries.Where(d => !d.Key).FirstOrDefault(); if (texts != null) { foreach (var item in texts) { multiContent.Add(new StringContent(item.Value, (encoder ?? Encoding.UTF8), "text/text"), item.Key); } } var files = queries.Where(d => d.Key).FirstOrDefault(); if (files != null) { foreach (var file in files) { multiContent.Add(new StreamContent(file.FileInfo.ReadToStream()), file.Key, file.FileInfo.Name); } } } } if (content.IsNull()) { content = new StringContent(string.Empty); } var stri = content.ReadAsStringAsync().Result; var t = client.PostAsync(url, content); t.Wait(); var result = t.Result.Content.ReadAsStreamAsync(); result.Wait(); client.Dispose(); return(result.Result); }