通过 HttpClient 在 API 中 POST 数据时出现问题

问题描述 投票:0回答:2

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

我的班级:

public class APICommands : IDisposable
{
    public APICommands()
    {
        this.HttpClientHandler = new HttpClientHandler();

        // Set authentication.
        this.HttpClientHandler.UseDefaultCredentials = false;
        this.HttpClientHandler.Credentials = new NetworkCredential("[email protected]", "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 - 期望失败”:(

你要去做什么?

c# .net dotnet-httpclient
2个回答
0
投票

身份验证机制似乎没有响应

401 - Unauthorized
响应。您可以将 PreAuthenticate 设置添加到 HttpClientHandler,以强制在初始请求期间发送凭据,而不是等待授权质询。

...
// Set authentication.
this.HttpClientHandler.UseDefaultCredentials = false;
this.HttpClientHandler.Credentials = new NetworkCredential("[email protected]",   "mypassword");
this.HttpClientHandler.PreAuthenticate = true;

0
投票

我认为

ServicePointManage.Expect100Continue
没有必要。我假设该凭证不起作用。

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

string authInfo = "[email protected]:mypassword";
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authInfo);
© www.soinside.com 2019 - 2024. All rights reserved.