gpt4 book ai didi

c# - 如何在没有用户名和密码但仅使用 token 的情况下访问 REST API 方法?

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

我正在尝试使用来自 c#/.net 的 token 访问/调用 REST API 中的方法,但我无法获得任何响应。我有很多 googlet - 但没有任何成功:-( 我是通过 REST API 调用方法的新手。

我有一个端点和一个 token ,我需要使用它们来与 REST API 通信。我需要通过这些方法在服务器上获取、发布、放置和删除数据

API 的输出为 JSON 格式。

也许这很简单 - 但我不知道该怎么做。

感谢任何帮助。

我尝试了以下解决方案 - 但没有成功:-(

        private static async void DoIt()
{
using (var stringContent = new StringContent("{ \"firstName\": \"Andy\" }", System.Text.Encoding.UTF8, "application/json"))
using (var client = new HttpClient())
{
try
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token);

// 1. Consume the POST command
var response = await client.PostAsync(endpoint, stringContent);
var result = await response.Content.ReadAsStringAsync();
//Console.WriteLine("Result from POST command: " + result);

// 2. Consume the GET command
response = await client.GetAsync(endpoint);
if (response.IsSuccessStatusCode)
{
var id = await response.Content.ReadAsStringAsync();
//Console.WriteLine("Result from GET command: " + result);
}
}
catch (Exception ex)
{
//Console.ForegroundColor = ConsoleColor.Red;
//Console.WriteLine(ex.Message);
//Console.ResetColor();
}
}
}

最佳答案

在您的代码中,您将 AuthenticationHeaderValue 初始化为“Basic”,这意味着基于用户名和密码的基本身份验证。如果您有 token ,则可以使用:

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", ACCESS_TOKEN);

用您拥有的 token 替换 ACCESS_TOKEN。

这是最可能的解决方案,但我在这里只能猜测,因为我不知道您尝试访问的 API。如果仍然不起作用,请尝试省略“Bearer”。

Reference

关于c# - 如何在没有用户名和密码但仅使用 token 的情况下访问 REST API 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57607497/

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