HttpClient使用方法(包括POST文件)
生活随笔
收集整理的這篇文章主要介紹了
HttpClient使用方法(包括POST文件)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
最近在做跨系統(tǒng)的數(shù)據(jù)交互業(yè)務(wù),從.Net的系統(tǒng)提交數(shù)據(jù)到Java的系統(tǒng)。
簡單的表單Get、POST都沒問題,但是有個功能是要提交普通文本和文件,試了好多都有問題,最后用HttpClient小折騰了一下就OK了。
?
①先說帶有文件的POST方法
public async void SendRequest() {HttpClient client = new HttpClient();client.MaxResponseContentBufferSize = 256000;client.DefaultRequestHeaders.Add("user-agent", "User-Agent Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; MALNJS; rv:11.0) like Gecko");//設(shè)置請求頭string url = ConfigurationManager.AppSettings["apiUrl"];HttpResponseMessage response;MultipartFormDataContent mulContent = new MultipartFormDataContent("----WebKitFormBoundaryrXRBKlhEeCbfHIY");//創(chuàng)建用于可傳遞文件的容器string path = "D:\\white.png";// 讀文件流FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);HttpContent fileContent = new StreamContent(fs);//為文件流提供的HTTP容器fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");//設(shè)置媒體類型mulContent.Add(fileContent, "myFile", "white.png");//這里第二個參數(shù)是表單名,第三個是文件名。如果接收的時候用表單名來獲取文件,那第二個參數(shù)就是必要的了 mulContent.Add(new StringContent("253"), "id"); //普通的表單內(nèi)容用StringContentmulContent.Add(new StringContent("english Song"), "desc"); response = await client.PostAsync(new Uri(url), mulContent); response.EnsureSuccessStatusCode(); string result = await response.Content.ReadAsStringAsync(); }??
看一下是如何接收的
public void ProcessRequest(HttpContext context) {var file = Request.Files["myFile"];var id = Request.Form["id"];//253var text = Request.Form["desc"];//english Songif (file != null && !String.IsNullOrEmpty(text)){file.SaveAs("/newFile/" + Guid.NewGuid().ToString() + "/" + file.FileName);//FileName是white.png }Response.Flush();Response.End(); }實在是相當(dāng)簡單
?
②POST普通表單請求
只需將設(shè)置Http正文和標(biāo)頭的操作替換即可
List<KeyValuePair<string, string>> pList = new List<KeyValuePair<string, string>>(); pList.Add(new KeyValuePair<string, string>("id", "253")); pList.Add(new KeyValuePair<string, string>("desc", "english Song")); HttpContent content = new FormUrlEncodedContent(pList); HttpResponseMessage response = await client.PostAsync(new Uri(url), content);?
③GET
string url = ConfigurationManager.AppSettings["apiUrl"]; string result = await client.GetStringAsync(new Uri(url+"?id=123"));?
轉(zhuǎn)載于:https://www.cnblogs.com/TiestoRay/p/4877978.html
《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的HttpClient使用方法(包括POST文件)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SQL Server 个人手册
- 下一篇: pLSQL中文乱码问题