简体   繁体   中英

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

I am trying to access the JSON response that the following code should generate:

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

The expected result looks like this.

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

When doing this in Postman or Javscript the result is correct, so I guess I am not capable of accessing the task string in a correct manner:-)

Any help pointing me in the right direction will be much appreciated.

Thnx

Your code contains more than one mistake.

Did you see HttpClient documentation?
Do you know about IDisposable ?
Do you know that collection of KeyValuePair is Dictionary ?

Don't use var keyword if you're not absolutely sure what are you doing. var can hide original problem from you and your question is example how var kills your time. I recommend using explicit types where possible.

And yes, as maintained above in comments you must unwrap string result from awaitable Task with await .

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

Usage

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
}

And finally, time to say Hello to Asynchronous programming . :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM