1、在百度智能云人脸识别创建应用后会获得API Key和Secret Key
2、根据API Key和Secret Key获取access_token
public class AuthService {
public static String getAuth() {
//自己的id和密钥
String clientId = "";
String clientSecret = "";
return getAuth(clientId, clientSecret);
}
public static String getAuth(String ak, String sk) {
String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
String getAccessTokenUrl = authHost
+ "grant_type=client_credentials"
+ "&client_id=" + ak
+ "&client_secret=" + sk;
try {
URL realUrl = new URL(getAccessTokenUrl);
HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
Map<String, List<String>> map = connection.getHeaderFields();
for (String key : map.keySet()) {
System.err.println(key + "--->" + map.get(key));
}
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String result = "";
String line;
while ((line = in.readLine()) != null) {
result += line;
}
System.err.println("result:" + result);
JSONObject jsonObject = JSONObject.parseObject(result);
String access_token = jsonObject.getString("access_token");
return access_token;
} catch (Exception e) {
e.printStackTrace(System.err);
}
return null;
}
}
3、需要把人脸图片转为base64格式
(1)将图片先转为字节文件
public static byte[] readFileByBytes(String filePath) throws IOException {
File file = new File(filePath);
if (!file.exists()) {
throw new FileNotFoundException(filePath);
} else {
ByteArrayOutputStream bos = new ByteArrayOutputStream((int)