HttpClient在API中POST数据的问题

时间:2014-03-18 18:38:56

标签: c# .net api dotnet-httpclient

当我发布数据时,我的代码显示以下错误:“错误: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 - 期望失败”:(

你要去的是什么?

...谢谢

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

为什么不通过授权标题尝试:

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