using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
class Program
{
static async Task Main(string[] args)
{
string tokenEndpoint = "https://";
string appKey = "aaa";
string appSecurity = "bbb";
try
{
using (HttpClient client = new HttpClient())
{
// 构建请求参数
var requestData = new StringContent(JsonConvert.SerializeObject(new Dictionary<string,string>
{
//{ "grant_type", "client_credentials" },
{ "appKey", appKey },
{ "appSecurity", appSecurity },
}), Encoding.UTF8, "application/json");
// 发送POST请求到Token端点
HttpResponseMessage response = await client.PostAsync(tokenEndpoint, requestData);
response.EnsureSuccessStatusCode();
// 读取响应内容并解析Token
string json = await response.Content.ReadAsStringAsync();
TokenResponseWrapper responseWrapper = JsonConvert.DeserializeObject<TokenResponseWrapper>(json);
TokenResponse tokenResponse = responseWrapper?.value;
if (tokenResponse != null)
{
Console.WriteLine("成功获取Token: {0}", tokenResponse.accessToken);
DateTimeOffset expireTime = DateTimeOffset.FromUnixTimeMilliseconds(tokenResponse.expireTime);
Console.WriteLine("过期时间: {0}", expireTime);
}
else
{
Console.WriteLine("获取Token失败");
}
}
}
catch (Exception ex)
{
Console.WriteLine("发生异常: " + ex.Message);
}
}
public class TokenResponse
{
public string accessToken { get; set; }
public string refreshToken { get; set; }
public long expireTime { get; set; }
public string corporationId { get; set; }
}
public class TokenResponseWrapper
{
public TokenResponse value { get; set; }
}
}
JSON值如:
{
"value": {
"accessToken": "aaa",
"refreshToken": "bbb",
"expireTime": ccc,
"corporationId": "ddd"
}
}