2016-05-06 124 views

回答

0

而不是HttpClient,也許你應該使用HttpWebRequest

它們提供了異步方法,並且可以通過設置method屬性來在後期切換。

e.g:

var request = (HttpWebRequest) WebRequest.Create(uri); 
request.Method = "POST"; 
var postStream = await request.GetRequestStreamAsync() 
2

使用HttpClient.PostAsync並且你可以通過HttpResponseMessage.Content.ReadAsStreamAsync()方法得到的響應流。

var message = await client.PostAsync(url, content); 
var stream = await message.Content.ReadAsStreamAsync(); 
+0

請注意,這會將整個流讀入內存。這大多不是用戶計劃使用流媒體時所期望的。 – lanwin

1

如果你想使用HttpClient用於流大量的數據,那麼你不應該使用PostAsync原因message.Content.ReadAsStreamAsync會讀取整個流到內存中。相反,您可以使用下面的代碼塊。

var message = new HttpRequestMessage(HttpMethod.Post, "http://localhost:3100/api/test"); 
var response = await client.SendAsync(message, HttpCompletionOption.ResponseHeadersRead); 
var stream = await response.Content.ReadAsStreamAsync(); 

這裏的關鍵是HttpCompletionOption.ResponseHeadersRead選項用於告訴客戶不讀取整個內容到內存中。