gpt4 book ai didi

c# - HttpClient 和设置授权 header

转载 作者:太空狗 更新时间:2023-10-29 17:37:51 26 4
gpt4 key购买 nike

我正在尝试向 Basecamp API 发出一个简单的请求,我按照提供的说明添加示例用户代理和我的凭据,但我不断收到 403 Forbidden 响应。

我的凭据绝对正确,请问是我的请求/凭据设置不正确吗?

这是我所拥有的(删除了个人信息):

var httpClient = new HttpClient();
var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("User-Agent", "MyApp [EMAIL ADDRESS]") });

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]"))));

var response = await httpClient.PostAsync("https://basecamp.com/[USER ID]/api/v1/projects.json", content);
var responseContent = response.Content;

using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
Console.WriteLine(await reader.ReadToEndAsync());
}

最佳答案

快速浏览一下他们的文档似乎表明 projects.json端点在 POST 正文中接受以下内容:

{
"name": "This is my new project!",
"description": "It's going to run real smooth"
}

您正在发送 User-Agent 作为 POST 正文。我建议您按如下方式更改代码:

    var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "[USERNAME]", "[PASSWORD]")));
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("User-Agent", "MyApp [EMAIL ADDRESS]");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
var response = await httpClient.PostAsJsonAsync(
"https://basecamp.com/[USER ID]/api/v1/projects.json",
new {
name = "My Project",
description = "My Project Description"
});

var responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}

这会发布文档中指定的有效负载,并在 header 中设置您的用户代理。

关于c# - HttpClient 和设置授权 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24609617/

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