默認情況下HttpClient中有緩存,在讀取流數據的時候,往往要等一小會兒,然后讀出一大堆。
我們在請求OpenAI類的大模型的時候,往往要一邊讀取一邊顯示(輸出),這時候需要禁止HttpClient 中內置的緩存功能。
其實就是在一步請求的時候加了一個“HttpCompletionOption.ResponseHeadersRead”參數而已。
示例代碼如下
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;public async Task SendPostRequestAsync(string url, string jsonData)
{using (HttpClient client = new HttpClient()){// 創建請求內容var content = new StringContent(jsonData, Encoding.UTF8, "application/json");// 創建 HttpRequestMessage 對象var request = new HttpRequestMessage(HttpMethod.Post, url){Content = content};// 發送請求并指定 HttpCompletionOption.ResponseHeadersReadusing (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)){response.EnsureSuccessStatusCode();// 獲取響應流using (Stream stream = await response.Content.ReadAsStreamAsync()){// 在這里處理流數據using (var reader = new StreamReader(stream)){string line;while ((line = await reader.ReadLineAsync()) != null){Console.WriteLine(line); // 輸出每行數據}}}}}
}