C# .NetCore 使用 Flurl.Http 与 HttpClient 请求处理流式响应

AI对话接口采用流式返回:

1、使用Flurl处理返回的数据流

using Flurl;

using Flurl.Http;

HttpPost

public async Task<string> GetLiushiChatLaw()

{

//1、请求参数,根据实际情况

YourModel request = new YourModel();string allStr = "";   string chatLawApiUrl = "http://请求地址";

//2、请求。接收类型流Stream,处理请求响应

using (var stream = await chatLawApiUrl.WithHeader("Content-Type", "application/json")

.SetQueryParams(new { access_token = "token" })

.PostJsonAsync(request)

.ReceiveStream())

{

// 逐块读取并处理响应内容

var buffer = new byte[102];

int bytesRead;

while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)

{

// 3、结果转换为字符串

string content = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);

allStr += content;

_logger.LogInformation(content);

}

}

return allStr;

}

2、HttpClient方式

public async Task<string> TestStream()

{

string url = "http://localhost:9291/api/Duix/GetStream";

string allStr = "";

DuixRequest duixRequest = new DuixRequest()

{

sid = "1234567890",

dh_question = "你好",

dh_conversation_id = "1234567890",

};

var client = new HttpClient();

using HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, url);

var response = await client.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseHeadersRead);

await using var stream = await response.Content.ReadAsStreamAsync();

var bytes = new byte[20];

int writeLength = 0;

string result = "";

while ((writeLength = stream.Read(bytes, 0, bytes.Length)) > 0)

{

string content = Encoding.UTF8.GetString(bytes, 0, writeLength);

result = result + content;

Console.Write(Encoding.UTF8.GetString(bytes, 0, writeLength));

}

Console.WriteLine();

Console.WriteLine("END");

return result;

}

参考文章:

C# 使用Flurl http请求处理流式响应 - ziff123 - 博客园

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

相关推荐
呆萌哈士奇3 小时前
告别 throw exception!为什么 Result<T> 才是业务逻辑的正确选择
c#·.net
海底星光5 小时前
c# 生产者消费者模式之内存/redis队列实现
redis·c#
kylezhao20197 小时前
C# 中实现自定义的窗口最大化、最小化和关闭按钮
开发语言·c#
月巴月巴白勺合鸟月半8 小时前
PDF转图片的另外一种方法
pdf·c#
m5655bj8 小时前
使用 C# 对比两个 PDF 文档的差异
pdf·c#·visual studio
Never_Satisfied8 小时前
C#插值字符串中大括号表示方法
前端·c#
wy31362282110 小时前
C#——意框架(结构说明)
前端·javascript·c#
kylezhao201910 小时前
C# 各种类型转换深入剖析
开发语言·c#
xb113211 小时前
Winform控件样式
c#
作孽就得先起床11 小时前
unity webGL导出.glb模型
unity·c#·游戏引擎·webgl