有些时候需要边请求边显示响应内容:
用httpClient.SendAsync(httpreq, HttpCompletionOption.ResponseHeadersRead);
private async void TestHttp() { DateTime d = DateTime.Now; HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.58"); httpClient.DefaultRequestHeaders.Add("Origin", "https://xxxx.com"); httpClient.DefaultRequestHeaders.Add("Referer", "https://xxxxx.com/"); StringContent jsonContent = new StringContent( JsonConvert.SerializeObject(new { data= "你们的发货地是哪里?", userId = "1211334", title = "test", usesyy = false }), Encoding.UTF8, "application/json"); var httpreq = new HttpRequestMessage(HttpMethod.Post, "https://xxxxxx") { Content = jsonContent }; var response = await httpClient.SendAsync(httpreq, HttpCompletionOption.ResponseHeadersRead); //var response = await httpClient.PostAsync("https://api.xxxxx", jsonContent); // 确保请求成功 //response.EnsureSuccessStatusCode(); string allStr = ""; // 读取响应内容的异步流 using (var responseStream = await response.Content.ReadAsStreamAsync()) { Debug.Print("============start response use minseconds=" + (DateTime.Now - d).TotalMilliseconds + " =================\r\n"); // 逐块读取并处理响应内容 var buffer = new byte[102]; int bytesRead; while ((bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length)) > 0) { // 处理响应内容 string content = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead); allStr += content; Debug.Print("---------------" + content + "\r\n"); } } var useTime = (DateTime.Now - d).TotalMilliseconds; var t2 = (DateTime.Now - DateTime.Now.AddMilliseconds(-100)).TotalMilliseconds; TestHttp(); }
标签:Now,C#,流式,DateTime,var,new,HttpClient,response,httpClient From: https://www.cnblogs.com/wgscd/p/17520540.html