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

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

相关推荐
code_shenbing37 分钟前
WPF 实现虚拟键盘
c#·wpf
软件黑马王子6 小时前
C#初级教程(4)——流程控制:从基础到实践
开发语言·c#
水煮庄周鱼鱼11 小时前
C# 入门简介
开发语言·c#
软件黑马王子12 小时前
Unity游戏制作中的C#基础(6)方法和类的知识点深度剖析
开发语言·游戏·unity·c#
Nicole Potter13 小时前
请说明C#中的List是如何扩容的?
开发语言·面试·c#
gu2014 小时前
c#编程:学习Linq,重几个简单示例开始
开发语言·学习·c#·linq
pchmi19 小时前
CNN常用卷积核
深度学习·神经网络·机器学习·cnn·c#
yuanpan19 小时前
23种设计模式之《组合模式(Composite)》在c#中的应用及理解
开发语言·设计模式·c#·组合模式
滴_咕噜咕噜20 小时前
C#基础总结:常用的数据结构
开发语言·数据结构·c#
万兴丶1 天前
Unity 适用于单机游戏的红点系统(前缀树 | 数据结构 | 设计模式 | 算法 | 含源码)
数据结构·unity·设计模式·c#