public class TokenInfo { public string access_token; // 令牌 public int expires_in; // 令牌有效期(秒) public string token_type; // 令牌类型 public string refresh_token; // 刷新令牌
public string error; // 错误代码 public string error_description; // 错误信息 }
这是API返回的JSON字串所对应的实体类。
下面的函数,就是调用登录API的具体代码:
private string GetWynToken(string apiUrl, string userName, string password) { var client = new System.Net.Http.HttpClient(); // API的调用者称为客户端(client),为了防止恶意调用, // 可在 http://localhost:51980/management 页面,管理允许调用API的客户端名称和授权码 string clientName = "integration"; string clientPassword = "eunGKas3Pqd6FMwx9eUpdS7xmz"; string authorizationString = clientName + ":" + clientPassword; byte[] byteArray = System.Text.ASCIIEncoding.ASCII.GetBytes(authorizationString); // 客户端授权信息应转成Base64String,放在请求头中 string base64 = System.Convert.ToBase64String(byteArray); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64); // 准备提交数据,即待验证的用户名和密码 string postData = "grant_type=password&username=" + userName + "&password=" + password; var postContent = new System.Net.Http.StringContent(postData, System.Text.Encoding.UTF8, "application/x-www-form-urlencoded"); // 调用 var res = client.PostAsync(apiUrl,postContent).Result; // 返回的结果是一个JSON字串 var resJson = res.Content.ReadAsStringAsync().Result; // 反序列化为TokenInfo对象 var ser = new System.Web.Script.Serialization.JavaScriptSerializer(); var tokenInfo = ser.Deserialize<TokenInfo>(resJson); // 调用失败或者密码不对,会返回error if (!string.IsNullOrWhiteSpace(tokenInfo.error)) return tokenInfo.error_description; // access_token属性值是真正的令牌 return tokenInfo.access_token; }