HttpClient異步Post請求,HttpClient.PostAsync(String, HttpContent, CancellationToken),String為Post的Url,HttpContent為發送到服務器的 HTTP 請求內容,就是Post過去的數據了。
HttpContent,常用的有FormUrlEncodedContent、StringContent。
FormUrlEncodedContent是以KeyValuePair形式出現的,假如你要傳遞的內容以KeyValue形式出現,可用。但一般應用中我們都是將實體轉成Json后傳遞的,誰還有哪個功夫一個個KeyValue對的寫啊。因此StringContent就是我經常使用的方法。
public async void aa() { JavaScriptSerializer jss = new JavaScriptSerializer(); string json = jss.Serialize(entity); string postUrl = "http://xxxx"; var content = new StringContent(json); var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; //創建HttpClient(注意傳入HttpClientHandler) using (var http = new HttpClient(handler)) { var response = await http.PostAsync(postUrl, content); //await異步等待回應 //await異步讀取最后的JSON(注意此時gzip已經被自動解壓縮了,因為上面的AutomaticDecompression = DecompressionMethods.GZip) string result = (await response.Content.ReadAsStringAsync());//result就是返回的結果。 } }
服務端:在Action中:
var stream = HttpContext.Current.Request.InputStream; byte[] byts = new byte[stream.Length]; stream.Read(byts, 0, (int)stream.Length); string postjson = Encoding.UTF8.GetString(byts); return postjson;//以UTF8形式獲取數據