以下是百度AI平台官方使用C#申请access_token的方法:
using System;
using System.Collections.Generic;
using System.Net.Http;
namespace com.baidu.ai
{
public static class AccessToken
{
// 调用getAccessToken()获取的 access_token建议根据expires_in 时间 设置缓存
// 返回token示例
public static String TOKEN = "24.adda70c11b9786206253ddb70affdc46.2592000.1493524354.282335-1234567";
// 百度云中开通对应服务应用的 API Key 建议开通应用的时候多选服务
private static String clientId = "百度云应用的AK";
// 百度云中开通对应服务应用的 Secret Key
private static String clientSecret = "百度云应用的SK";
public static String getAccessToken() {
String authHost = "https://aip.baidubce.com/oauth/2.0/token";
HttpClient client = new HttpClient();
List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>();
paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
paraList.Add(new KeyValuePair<string, string>("client_id", clientId));
paraList.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
String result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);
return result;
}
}
}
可见,返回的json文件已经被转化为String类型,保存在result里面,我们需要的access_token就混在其中:
{
“refresh_token”: “25.b55fe1d287227ca97aab219bb249b8ab.315360000.1798284651.282335-8574074”,
“expires_in”: 2592000,
“scope”: “public wise_adapt”,
“session_key”: “9mzdDZXu3dENdFZQurfg0Vz8slgSgvvOAUebNFzyzcpQ5EnbxbF+hfG9DQkpUVQdh4p6HbQcAiz5RmuBAja1JJGgIdJI”,
"access_token": “24.6c5e1ff107f0e8bcef8c46d3424a0e78.2592000.1485516651.282335-8574074”,
“session_secret”: “dfac94a3489fe9fca7c3221cbf7525ff”
}
一种简单的分离方法是:可以对分号(")进行分割,得到分割后的数组,再找出access_token所在的数组位置i,其值就是i+2。代码如下:
string[] divide = result.Split(new char[] { '"' });
string tk = "Error";
for(int i = 0; i < divide.Length; i++)
{
if(divide[i]== "access_token")
{
tk = divide[i + 2];
break;
}
}
return tk;