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 - 博客园

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

相关推荐
我好喜欢你~2 小时前
C#---StopWatch类
开发语言·c#
一阵没来由的风6 小时前
拒绝造轮子(C#篇)ZLG CAN卡驱动封装应用
c#·can·封装·zlg·基础封装·轮子
一枚小小程序员哈12 小时前
基于微信小程序的家教服务平台的设计与实现/基于asp.net/c#的家教服务平台/基于asp.net/c#的家教管理系统
后端·c#·asp.net
Eternity_GQM13 小时前
【Word VBA Zotero 引用宏错误分析与改正指南】【解决[21–23]参考文献格式插入超链接问题】
开发语言·c#·word
cimeo18 小时前
【C 学习】06-算法&程序设计举例
c#
百锦再19 小时前
.NET 的 WebApi 项目必要可配置项都有哪些?
java·开发语言·c#·.net·core·net
WYH2871 天前
C#控制台输入(Read()、ReadKey()和ReadLine())
开发语言·c#
hqwest1 天前
C#WPF实战出真汁06--【系统设置】--餐桌类型设置
c#·.net·wpf·布局·分页·命令·viewmodel
做一位快乐的码农1 天前
基于.net、C#、asp.net、vs的保护大自然网站的设计与实现
c#·asp.net·.net
DavieLau1 天前
C#项目WCF接口暴露调用及SOAP接口请求测试(Python版)
xml·服务器·开发语言·python·c#