基于JAVA1.8,使用maven进行版本控制
1.在百度开发者中心注册账户,并且申请“通用文字识别”项目(同样可以申请其它项目,部分需要收费),申请完成后进入控制台管理应用,会自动生成API Key 和 Secret Key,用于生成access_token。
2.在pom文件中添加依赖
<dependencies>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
</dependencies>
3.获取access_token
参考文档:http://ai.baidu.com/docs#/Auth/top
注:参考文档中有各种语言的实例代码,此处以JAVA为例
向授权服务地址https://aip.baidubce.com/oauth/2.0/token
发送请求(推荐使用POST),并在URL中带上以下参数:
- grant_type: 必须参数,固定为
client_credentials
; - client_id: 必须参数,应用的
API Key
; - client_secret: 必须参数,应用的
Secret Key
;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
public class AuthService {
public static String getAuth() {
// 官网获取的 API Key 更新为你注册的
String clientId = "(此处需自己填写)";
// 官网获取的 Secret Key 更新为你注册的
String clientSecret = "(此处需自己填写)";
return getAuth(clientId, clientSecret);
}
/**
* 获取API访问token
* 该token有一定的有效