gpt4 book ai didi

c# - HttpClient post 在 c# 中返回错误的请求,在 postman 中工作

转载 作者:行者123 更新时间:2023-12-02 00:17:58 25 4
gpt4 key购买 nike

我正在尝试访问休息端点,https://api.planet.com/auth/v1/experimental/public/users/authenticate .它在请求正文中期待 json。

我可以获得在 Postman 中工作的请求,但不能使用 C#。使用 postman ,我收到了预期的无效电子邮件或密码消息,但无论我尝试什么,我的代码都收到“错误请求”。

这是发出请求的代码

private void Login()
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://api.planet.com/");
client.DefaultRequestHeaders.Accept.Clear();
//ClientDefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
Data.User user = new Data.User
{
email = "myemail@company.com",
password = "sdosadf"
};
var requestMessage = JsonConvert.SerializeObject(user);
var content = new StringContent(requestMessage, Encoding.UTF8, "application/json");
var response = client.PostAsync("auth/v1/experimental/public/users/authenticate", content).Result;
Console.WriteLine(response.ToString());
}
catch (WebException wex )
{
MessageBox.Show(wex.Message) ;
}
}
class User
{
public string email;
public string password;
}

这是正在工作的 Postman 的屏幕截图 enter image description here

enter image description here

最佳答案

使它起作用的方法是改变内容标题“content-type”。默认情况下 HTTPClient 正在创建 content-type: application/json;characterset= UTF8。我删除并重新创建了没有字符集部分的内容标题,它起作用了。

content.Headers.Remove("Content-Type");
content.Headers.Add("Content-Type", "application/json");

关于c# - HttpClient post 在 c# 中返回错误的请求,在 postman 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56501046/

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