C# 调用webApi接口的方法(类库RestSharp)
一、类库RestSharp,用于发送http请求
依赖于Newtonsoft.Json、RestSharp,需要去NuGet安装;Newtonsoft.Json用于JSON串的生成和反向解析,RestSharp用于发起HTTP请求。
二、请求方式
引入using Newtonsoft.Json与using RestSharp才可以使用具体功能
using Newtonsoft.Json; using RestSharp; namespace WenXinYiYanTest { //封装的方法对象,便于声明调阅 public class ERNIE35 { //HTTP请求方法,示例为文心一言的模型服务调阅请求 public string ERNIE35_8K(string usercontent,string access_token) { //新建连接请求的地址 var client = new RestClient($"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=" + access_token.Trim().ToString()); //设定请求的Timeout client.Timeout = -1; //设定请求的方式POST\GET等 var request = new RestRequest(Method.POST); //设定Content-Type request.AddHeader("Content-Type", "application/json"); //组合请求JSON串 ERNIE35JSON eRNIE35JSON = new ERNIE35JSON(); messagesList messagesList = new messagesList(); messagesList.role = "user"; messagesList.content = usercontent.Trim().ToString(); eRNIE35JSON.messages = messagesList; var body = JsonConvert.SerializeObject(eRNIE35JSON); //JSON串格式调整 body = body.Replace(":{",":[{"); body = body.Replace("}}", "}]}"); //添加Body体内容,上述的JSON串内容 request.AddParameter("application/json", body, ParameterType.RequestBody); //访问接口,并获取返回对象 IRestResponse response = client.Execute(request); //获取反参JSON传,并解析为JSON对象 var result = JsonConvert.DeserializeObject<dynamic>(response.Content); //返回串中 主体内容 return result.result; } } }
ERNIE35JSON、messagesList类对象:
public class ERNIE35JSON { public messagesList messages {get; set; } } public class messagesList { public string role { get; set; } public string content { get; set; } }
最终生成的JSON格式为:
{"messages":{"role":"user","content":"请求会话的内容"}} 调整后 {"messages":[{"role":"user","content":"请求会话的内容"}]}
JsonConvert.DeserializeObject<dynamic>(response.Content)可以实现返回的JSON串反向为运行时的对象,免于设置其对应的对象类,通过result.节点名称获取对应的值。
拓展:
C# 调用webApi接口的方法(类库HttpClient)