gpt4 book ai didi

c# - 如何在 C# 中使用 rest api

转载 作者:太空宇宙 更新时间:2023-11-03 22:59:04 25 4
gpt4 key购买 nike

我想在我的项目 (web)/Windows 服务 (C#) 中使用具有 post 方法的 rest api。

Url : https://sampleurl.com/api1/token

我需要传递用户名和密码来生成 token 。我写过这样的代码。

string sURL = "https://sampleurl.com/api1/token/Actualusername/Actualpassword";
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(sURL);

wrGETURL.Method = "POST";
wrGETURL.ContentType = @"application/json; charset=utf-8";
wrGETURL.ContentLength = 0;
HttpWebResponse webresponse = wrGETURL.GetResponse() as HttpWebResponse;

Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
// read response stream from response object
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(), enc);
// read string from stream data
string strResult = loResponseStream.ReadToEnd();
// close the stream object
loResponseStream.Close();
// close the response object
webresponse.Close();

Response.Write(strResult);

我收到错误:无法建立连接,因为目标机器主动拒绝了它

在 C# 中使用 rest api 是正确的方法吗?

最佳答案

这在很大程度上取决于 API 的文档,而是将数据写入请求主体,获取请求流,然后将字符串写入流。同样,这取决于您使用什么 API 进行身份验证,而我不知道哪个是我的猜测。

        string sURL = "https://sampleurl.com/api1/token";
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(sURL);

wrGETURL.Method = "POST";
wrGETURL.ContentType = @"application/json; charset=utf-8";
using (var stream = new StreamWriter(wrGETURL.GetRequestStream()))
{
var bodyContent = new
{
username = "Actualusername",
password = "Actualpassword"
}; // This will need to be changed to an actual class after finding what the specification sheet requires.

var json = JsonConvert.SerializeObject(bodyContent);

stream.Write(json);
}
HttpWebResponse webresponse = wrGETURL.GetResponse() as HttpWebResponse;

Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
// read response stream from response object
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(), enc);
// read string from stream data
string strResult = loResponseStream.ReadToEnd();
// close the stream object
loResponseStream.Close();
// close the response object
webresponse.Close();

Response.Write(strResult);

关于c# - 如何在 C# 中使用 rest api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44017736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com