HttpClient帖子在C#中返回错误请求,可在邮递员中使用

时间:2019-06-07 20:47:16

标签: c# rest dotnet-httpclient

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

我可以请求在Postman中工作,但不能使用c#。使用邮递员,我会收到预期的无效电子邮件或密码消息,但是无论尝试如何,使用我的代码我都会收到“错误请求”。

这是发出请求的代码

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

3 个答案:

答案 0 :(得分:1)

问题是您尝试调用async方法而不等待使用await methodvar task = method; task.Wait()的响应,因此,当您最终执行response.ToString()时,它将返回您看到的文字。

在非异步方法中处理此问题的一种方法是执行以下操作:

var task = client.PostAsync("auth/v1/experimental/public/users/authenticate", content);
task.Wait();
var responseTask = task.Content.ReadAsStringAsync();
responseTask.Wait();
Console.WriteLine(responseTask.Result);

另一种方法是通过执行private async void Login()然后执行以下操作来使当前方法异步:

var postResp = await client.PostAsync("auth/v1/experimental/public/users/authenticate", content);
var response = await postResp.Content.ReadAsStringAsync();
Console.WriteLine(response);

答案 1 :(得分:1)

使其工作的方法是更改​​内容标头“ content-type”。默认情况下,public static bool IsIntegral(this Type type) { var typeCode = (int) Type.GetTypeCode(type); return typeCode > 4 && typeCode < 13; } 正在创建HTTPClient。我放下并重新创建了内容标头,它可以正常工作。

content-type: application/json;characterset= UTF8

答案 2 :(得分:0)

创建这样的方法...

launch.json

调用您的方法

    static async Task<string> PostURI(Uri u, HttpContent c)
    {            

        var response = string.Empty;
        var msg = "";
        using (var client = new HttpClient())
        {
            HttpResponseMessage result = await client.PostAsync(u, c);
             msg = await result.Content.ReadAsStringAsync();              
            if (result.IsSuccessStatusCode)
            {                   
                response = result.StatusCode.ToString();                    

            }
        } 
        return response;
    }