簡體   English   中英

HttpClient post 在 C# 中返回錯誤的請求,在郵遞員中工作

[英]HttpClient post returns bad request in c#, works in postman

我正在嘗試訪問休息端點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 的屏幕截圖在此處輸入圖片說明

在此處輸入圖片說明

使其工作的方法是更改​​內容標題“內容類型”。 默認情況下HTTPClient正在創建content-type: application/json;characterset= UTF8 我刪除並重新創建了沒有字符集部分的內容標題,並且它起作用了。

content.Headers.Remove("Content-Type");
content.Headers.Add("Content-Type", "application/json");

問題是您正在嘗試調用async方法而不等待使用await methodvar task = method; task.Wait()的響應var task = method; task.Wait() var 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);

創建一個這樣的方法......

    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;
    }

在你的方法中調用

public void Login()
    {
        string postData ="{\"email\":\"your_email\",\"password\":\"your_password\"}";
        Uri u = new Uri("yoururl");
        var payload = postData;

        HttpContent c = new StringContent(payload, Encoding.UTF8,"application/json");
        var t = Task.Run(() => PostURI(u, c));
        t.Wait();
        Response.Write(t.Result);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM