HTTP streaming response is a server block transmission technology that allows the client to start processing when it receives the first block of data without waiting until all the data is transmitted. It is commonly used in large model session requests.
Code example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
using var client = httpFactory.CreateClient();
client.DefaultRequestVersion = HttpVersion.Version20;
client.DefaultRequestHeaders.Authroization = new AuthenticationHeaderValue("Bearer", apiKey);
try
{
using var request = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new StringContent(body, Encoding.UTF8, "application/json")
};
using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); // Wait until the response header is returned
using var stream = await response.Content.ReadAsStreamAsync();
using var reader = new StreamReader(stream);
while (!reader.EndOfStream)
{
var content = await reader.ReadLineAsync();
if (!string.IsNullOrEmpty(content))
{
// data: {...}
// Processing Data
}
}
}
catch (Exception ex)
{
// ...
}
|