HttpWebRequest实现通用的Post提交,传递header,token等 电脑版发表于:2021/12/12 12:56 #### 封装的代码如下: ``` /// <summary> /// HttpWebRequest实现的通用的Post提交,传递header,token等 /// </summary> /// <param name="Url"></param> /// <param name="Pram"></param> /// <param name="json"></param> /// <returns></returns> public static string HttpPost(string Url, Dictionary<string, string> Pram, string json, string token) { string PageStr = string.Empty; Url += "?"; foreach (var item in Pram) { Url += item.Key + "=" + item.Value + "&"; } Uri url = new Uri(Url.TrimEnd('&')); byte[] reqbytes = Encoding.UTF8.GetBytes(json); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Headers.Add("Authorization", $"Bearer {token}"); req.Method = "post"; // req.ContentType = "application/x-www-form-urlencoded"; req.ContentType = "application/json"; req.ContentLength = reqbytes.Length; Stream stm = req.GetRequestStream(); stm.Write(reqbytes, 0, reqbytes.Length); stm.Close(); HttpWebResponse wr = (HttpWebResponse)req.GetResponse(); Stream stream = wr.GetResponseStream(); StreamReader srd = new StreamReader(stream, Encoding.UTF8); PageStr += srd.ReadToEnd(); srd.Close(); return PageStr; } ``` #### 调用示例 ``` public static void ChatQ(string question) { var dic = new Dictionary<string, Object>(); dic.Add("prompt", question); dic.Add("model", "text-davinci-003"); dic.Add("max_tokens", 2000); dic.Add("temperature", 0.5); var s = HttpPost("https://api.openai.com/v1/completions", new Dictionary<string, string>(), JsonConvert.SerializeObject(dic), "你的token"); //Console.WriteLine(s); var result = Newtonsoft.Json.JsonConvert.DeserializeObject<OpenAI_Response>(s); Console.WriteLine("回答: " + result.choices[0].text); } ```