我正在尝试使用 C# HttpClient 类发出 API 请求。
我设法从 API 请求获得 OK 响应,但现在我想处理该响应内容以获取用户信息。
这是我的代码:
private async void GetRefreshToken()
{
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://www.strava.com/oauth/token"))
{
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new StringContent(CONSTANTS.CLIENT_ID), "client_id");
multipartContent.Add(new StringContent(CONSTANTS.CLIENT_SECRET), "client_secret");
multipartContent.Add(new StringContent(userCtrl.StravaAuthToken), "code");
multipartContent.Add(new StringContent(""), "grant_type");
request.Content = multipartContent;
var response = await httpClient.SendAsync(request);
}
}
}
解析为字符串的响应变量返回以下内容:
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Transfer-Encoding: chunked
Connection: keep-alive
X-Download-Options: noopen
Status: 200 OK
X-Request-Id: d9fc7423-4d6b-2342-9d3a-614fd583e008
Referrer-Policy: strict-origin-when-cross-origin
X-FRAME-OPTIONS: DENY
X-Content-Type-Options: nosniff
X-Permitted-Cross-Domain-Policies: none
Vary: Origin
X-XSS-Protection: 1; mode=block
Cache-Control: must-revalidate, max-age=0, private
Date: Mon, 13 Apr 2020 11:08:57 GMT
ETag: W/"01b8306a9b65e970f36bacbec682342f9"
Via: 1.1 linkerd
Content-Type: application/json; charset=utf-8
}
但是当我与 Postman 核实时,API 响应的内容应该如下所示。我想获取刷新和访问令牌:
{
"token_type": "Bearer",
"expires_at": 1586793993,
"expires_in": 18150,
"refresh_token": "a6a5s7d5as8dasdad75a7d5757a5d7asd67576ae",
"access_token": "a9sdas87da9s8d7asd9a7s9d7as9d7as7d97asd7",
"athlete": {
"id": 878960,
"username": "username",
"resource_state": 2,
"firstname": "Name",
"lastname": "Lastname",
"city": null,
"state": null,
"country": null,
"sex": "M",
"premium": false,
"summit": false,
"created_at": "2019-08-01T14:53:11Z",
"updated_at": "2019-08-01T14:54:00Z",
"badge_type_id": 0,
"profile_medium": "https://lh3.googleusercontent.com/a-/AOh14dfgdfg233WZ_rdRmLMbLnqKKoytbxH-UBm",
"profile": "https://lh3.googleusercontent.com/a-/AOh14GhrEsdfgs3WZ_rdRmLMbLnqKKoytbxH-UBm",
"friend": null,
"follower": null
}
}
我认为使用我的代码,我只能从 API 请求中获取状态,而不是其内容。如果是的话,如何从API请求中获取内容并解析为JSON格式?
谢谢,我对 API 世界 100% 陌生,所以请做简单的解释:D
要获取 json 字符串,请使用
await response.Content.ReadAsStringAsync()
。然后,您可以将其解析为 json 字符串并找到令牌(Json.NET 可以提供帮助)。