gpt4 book ai didi

c# - 如何使用HttpClient认证发帖

转载 作者:IT王子 更新时间:2023-10-29 04:18:50 27 4
gpt4 key购买 nike

我正在尝试使用 HttpClient 在 C# 中执行以下 curl(对我有用)。

curl -X POST http://www.somehosturl.com \
-u <client-id>:<client-secret> \
-d 'grant_type=password' \
-d 'username=<email>' \
-d 'password=<password>' \
-d 'scope=all

C#代码:

HttpClientHandler handler = new HttpClientHandler { Credentials = new  
System.Net.NetworkCredential ("my_client_id", "my_client_secret")
};


try
{
using(var httpClient = new HttpClient(handler))
{
var activationUrl = "www.somehosturl.com";

var postData = "grant_type=password&username=myemail@myemail.com&password=mypass&scope=all";
var content = new StringContent(postData, Encoding.UTF8, "application/x-www-form-urlencoded");

var response = await httpClient.PostAsync(activationUrl, content);
if(!response.IsSuccessStatusCode)
return null;

var result = await response.Content.ReadAsStringAsync();

return result;
}
}
catch(Exception)
{
return null;
}

执行时直接崩溃,连异常都没有捕获

通常我能够完美地获取和发布,但让我失望的是如何设置身份验证内容(客户端 ID 和客户端密码)

最佳答案

首先你必须设置 Authorization -标题为您的 <clientid><clientsecret> .

而不是使用 StringContent你应该使用 FormUrlEncodedContent如下图:

var client = new HttpClient();
client.BaseAddress = new Uri("http://myserver");
var request = new HttpRequestMessage(HttpMethod.Post, "/path");

var byteArray = new UTF8Encoding().GetBytes("<clientid>:<clientsecret>");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

var formData = new List<KeyValuePair<string, string>>();
formData.Add(new KeyValuePair<string, string>("grant_type", "password"));
formData.Add(new KeyValuePair<string, string>("username", "<email>"));
formData.Add(new KeyValuePair<string, string>("password", "<password>"));
formData.Add(new KeyValuePair<string, string>("scope", "all"));

request.Content = new FormUrlEncodedContent(formData);
var response = await client.SendAsync(request);

关于c# - 如何使用HttpClient认证发帖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30858890/

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