C# 使用HttpCilent请求接口,传递表单数据(可上传图片)
我看httpClient现在都用的很多了,好处应该是对比web request性能更好,异步请求更方便简单吧。
记录一下post请求。上传图片主要是用地stream流;
//上传图片到服务器 HttpClient client = new HttpClient(); MultipartFormDataContent form = new MultipartFormDataContent();//表单 StreamContent fileContent = new StreamContent(stream);//图片stream fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data"); fileContent.Headers.ContentDisposition.FileName = System.DateTime.Now.ToString("yyyMMddHHmmss") + new Random().Next(1000, 9999) + ".jpg"; form.Add(fileContent); string url = "http://" + authorizeModel.url + "/Login/UploadFile";//接口 HttpResponseMessage res = await client.PostAsync(url, form); var result = await res.Content.ReadAsStringAsync();