百度API连接分为两步:
1、使用API key和secret key获取token
2、连接调用方法。
1、获取token。
public static String getAuth() {
// 官网获取的 API Key 更新为你注册的
String clientId = "XP8YaCKuqZW7GIfEf05iFa";
// 官网获取的 Secret Key 更新为你注册的
String clientSecret = "jrFmEH4VX9MsSUaEFm7LH0tGZt1B7";
return getAuth(clientId, clientSecret);
}
/**
* 获取API访问token
* 该token有一定的有效期,需要自行管理,当失效时需重新获取.
* @param ak - 百度云官网获取的 API Key
* @param sk - 百度云官网获取的 Securet Key
* @return assess_token 示例:
* "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
*/
public static String getAuth(String ak, String sk) {
// 获取token地址
String authHost = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials";
String getAccessTokenUrl = authHost+ "&client_id=" + ak + "&client_secret=" + sk;
try {
URL realUrl = new URL(getAccessTokenUrl);
HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String result = "";
String line;
while ((line = in.readLine()) != null) {
result += line;
}
JSONObject jsonObject = new JSONObject(result);
String access_token = jsonObject.getString("access_token");
return access_token;
} catch (Exception e) {
e.printStackTrace(System.err);
}
return null;
}
2、连接:识别图片中的文字
public static void main(String[] args) {
File file = new File("d:/test.jpg");
String imageBase = encodeImgageToBase64(file);
imageBase = imageBase.replaceAll("\r\n","");
imageBase = imageBase.replaceAll("\\+","%2B");
String httpUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token=24.6cc81615b0f0940b002f39bb3ee08.2592000.1519375458.282335-10719029";
String httpArg = "image="+imageBase;
String res = request(httpUrl, httpArg);
}
public static String request(String httpUrl, String httpArg) {
BufferedReader reader = null;
StringBuffer sbf = new StringBuffer();
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setDoOutput(true);
connection.getOutputStream().write(httpArg.getBytes("UTF-8"));
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return sbf.toString();
}
public static String encodeImgageToBase64(File imageFile) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
// 其进行Base64编码处理
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = new FileInputStream(imageFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
return new BASE64Encoder().encode(data);// 返回Base64编码过的字节数组字符串
}