/// <summary> /// 后端模拟网页表单提交数据 /// </summary> /// <returns></returns> public string TestFormPost() { using (HttpClient client = new HttpClient()) { using (var content = new MultipartFormDataContent()) { //字段 NameValueCollection nvCollect = new NameValueCollection(); nvCollect.Add("Parameter", "这是普通值"); var parameter = new List<ByteArrayContent>(); foreach (var key in nvCollect.AllKeys) { var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(nvCollect[key])); dataContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { Name = key }; parameter.Add(dataContent); }; //文件 var file = new List<ByteArrayContent>(); new ByteArrayContent(System.Text.Encoding.Default.GetBytes("文本文件内容")).Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "LogFileName.txt" }; var aciont = new Action<List<ByteArrayContent>>((parameterData) => { foreach (var param in parameterData) { file.Add(param); } }); //拼接表单值 aciont(parameter); aciont(file); var responseResult = client.PostAsync("地址" + "/api", content).Result; return responseResult.Content.ReadAsStringAsync().Result;//线程异步结果 } } }
原文地址:https://www.cnblogs.com/liyiboke/p/10000245.html
时间: 2024-10-22 21:00:30