通过HttpClient在API中POST数据的问题

本文关键字:数据 问题 POST HttpClient API 通过 | 更新日期: 2023-09-27 17:50:53

我的代码显示以下错误:"错误:401未授权"当我发布数据。

我的类:

public class APICommands : IDisposable
{
    public APICommands()
    {
        this.HttpClientHandler = new HttpClientHandler();
        // Set authentication.
        this.HttpClientHandler.UseDefaultCredentials = false;
        this.HttpClientHandler.Credentials = new NetworkCredential("username@myemail.com", "mypassword");
        this.HttpClient = new HttpClient(this.HttpClientHandler);
        this.HttpClient.BaseAddress = new Uri("https://api.myhost.com");
        this.HttpClient.DefaultRequestHeaders.Accept.Clear();
        this.HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }
    private HttpClient HttpClient { get; set; }
    private HttpClientHandler HttpClientHandler { get; set; }
    public async Task<JsonResultBoleto> CreateClient(string name, string age)
    {
        ServicePointManager.Expect100Continue = false;
        var postData = new List<KeyValuePair<string, string>>();
        postData.Add(new KeyValuePair<string, string>("name", name));
        postData.Add(new KeyValuePair<string, string>("age", age));
        HttpContent content = new FormUrlEncodedContent(postData);
        // When I call this method "PostAsync", the error message is displayed.
        HttpResponseMessage response = await this.HttpClient.PostAsync("https://api.myhost.com/client/", content);
        if (response.IsSuccessStatusCode)
        {
           // Do something.
        }
        return null;
    }
}

当我添加这段代码时,错误开始了:ServicePointManager.Expect100Continue = false;。我添加了这段代码来解决另一个错误:"417 -期望失败":(

你要去哪里?

谢谢…

通过HttpClient在API中POST数据的问题

看来身份验证机制没有响应401 - Unauthorized响应。您可以将PreAuthenticate设置添加到HttpClientHandler中,以在初始请求期间强制发送凭据,而不是等待授权挑战。

...
// Set authentication.
this.HttpClientHandler.UseDefaultCredentials = false;
this.HttpClientHandler.Credentials = new NetworkCredential("username@myemail.com",   "mypassword");
this.HttpClientHandler.PreAuthenticate = true;

我认为不需要ServicePointManage.Expect100Continue。我想凭证不起作用。

为什么不尝试通过授权头:

string authInfo = "username@myemail.com:mypassword";
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authInfo);