簡體   English   中英

HttpClient 任務按預期返回 System.Threading.Tasks.Task`1[System.String] 而不是 JSON

[英]HttpClient Task returning System.Threading.Tasks.Task`1[System.String] and not JSON as expected

我正在嘗試訪問以下代碼應生成的 JSON 響應:

public static async Task<string> GetResponseString(string refreshToken)
    {
        var client = new HttpClient();
        client.BaseAddress = new Uri("https://www.strava.com");
        var request = new HttpRequestMessage(HttpMethod.Post, "/oauth/token");

        var keyValues = new List<KeyValuePair<string, string>>();
        keyValues.Add(new KeyValuePair<string, string>("client_id", "some_id"));
        keyValues.Add(new KeyValuePair<string, string>("client_secret", "some_secret"));
        keyValues.Add(new KeyValuePair<string, string>("refresh_token", refreshToken));
        keyValues.Add(new KeyValuePair<string, string>("grant_type", "refresh_token"));

        request.Content = new FormUrlEncodedContent(keyValues);
        var response = await client.SendAsync(request);
        var result = await response.Content.ReadAsStringAsync();

        return result;
    }

預期結果如下所示。

    {
  "token_type": "Bearer",
  "access_token": "a9b723...",
  "expires_at":1568775134,
  "expires_in":20566,
  "refresh_token":"b5c569..."
}

在 Postman 或 Javscript 中執行此操作時,結果是正確的,所以我想我無法以正確的方式訪問任務字符串:-)

任何為我指明正確方向的幫助將不勝感激。

謝謝

您的代碼包含多個錯誤。

您看到HttpClient文檔了嗎?
你知道IDisposable嗎?
你知道KeyValuePair的集合是Dictionary嗎?

如果您不確定自己在做什么,請不要使用var關鍵字。 var可以向您隱藏原始問題,而您的問題是var如何消磨您的時間的示例。 我建議盡可能使用顯式類型。

是的,正如上面在評論中所維護的,您必須使用await解開可等待Taskstring結果。

private static readonly HttpClient client = new HttpClient();

private static async Task<string> GetResponseStringAsync(string url, Dictionary<string, string> formData)
{
    using (HttpContent content = new FormUrlEncodedContent(formData))
    using (HttpResponseMessage response = await client.PostAsync(url, content))
    {
         response.EnsureSuccessStatusCode();
         return await response.Content.ReadAsStringAsync();
    }
}

用法

Dictionary<string, string> postData = new Dictionary<string, string>();
postData.Add("client_id", "some_id");
postData.Add("client_secret", "some_secret");
postData.Add("refresh_token", refreshToken);
postData.Add("grant_type", "refresh_token");

try
{
    string result = await GetResponseStringAsync("https://www.strava.com/oauth/token", postData);
    // success here
}
catch (Exception ex)
{
    Debug.WriteLine(ex.Message);
    // request failed
}

最后,是時候向異步編程問好。 :)

暫無
暫無

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

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