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

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

相关推荐
上位机付工4 小时前
C#与倍福TwinCAT3进行ADS通信
开发语言·c#
土了个豆子的5 小时前
02.继承MonoBehaviour的单例模式基类
开发语言·visualstudio·单例模式·c#·里氏替换原则
疯狂的维修5 小时前
c#中public类比博图
c#·自动化
土了个豆子的8 小时前
03.缓存池
开发语言·前端·缓存·visualstudio·c#
太阳伞下的阿呆9 小时前
HttpClient、OkHttp 和 WebClient
okhttp·httpclient·webclient
somethingGoWay13 小时前
wpf .netcore 导出docx文件
wpf·.netcore
somethingGoWay16 小时前
wpf .netcore 导出pdf文件
pdf·wpf·.netcore
xiaowu0801 天前
策略模式-不同的鸭子的案例
开发语言·c#·策略模式
VisionPowerful1 天前
九.弗洛伊德(Floyd)算法
算法·c#
ArabySide1 天前
【C#】 资源共享和实例管理:静态类,Lazy<T>单例模式,IOC容器Singleton我们该如何选
单例模式·c#·.net core