springboot项目集成百度api:
实现证件及票据识别.
项目结构:
pom.xml
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.2.2.RELEASE
com.ssj
baiduapi
0.0.1-SNAPSHOT
baiduapi
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter
com.alibaba
fastjson
1.2.46
org.apache.httpcomponents
httpclient
4.5.5
commons-codec
commons-codec
1.12
org.apache.commons
commons-lang3
commons-beanutils
commons-beanutils
1.9.3
commons-io
commons-io
2.6
com.auth0
java-jwt
3.4.0
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-freemarker
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.boot
spring-boot-maven-plugin
controller
package com.ssj.baiduapi.xaingmu;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ssj.baiduapi.xaingmu.config.AuthService;
import com.ssj.baiduapi.xaingmu.config.Currency;
import com.ssj.baiduapi.xaingmu.config.Directional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.net.URISyntaxException;
@RestController
public class BaiDUController {
@RequestMapping(value = "baiDuApi", method = RequestMethod.POST)
public JSONObject baiDuApi(@RequestBody String data) throws IOException, URISyntaxException {
JSONObject json = new JSONObject();
String path = "";
String type = "";
// front:身份证含照片的一面;back:身份证带国徽的一面
String idCardSide = "";
if (StringUtils.isNotBlank(data)) {
JSONObject jsonObject = JSON.parseObject(data);
path = jsonObject.getString("path");
type = jsonObject.getString("type");
idCardSide = jsonObject.getString("idCardSide");
}
Directional directional = new Directional();
String token = directional.takeString(type,idCardSide);
if (token.equals("")){
json.put("json","类型传输不正确");
return json;
}else {
AuthService authService = new AuthService();
String auth = authService.getAuth();
token+="access_token="+auth;
}
Currency currency = new Currency();
String str = currency.checkFile(path, token);
json.put("json",str);
return json;
}
}
工具类
Directional
package com.ssj.baiduapi.xaingmu.config;
public class Directional {
public static String takeString(String tag,String idCardSide){
String DECS_URL = "";
switch (tag){
case "1" :
// 身份证
DECS_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?id_card_side="+idCardSide+"&";
break;
case "2" :
// 营业执照
DECS_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_license?";
break;
case "3":
// 通用票据识别
DECS_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/receipt?";
break;
case "4":
// 增值税发票
DECS_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice?";
break;
case "5":
// 定额发票
DECS_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/quota_invoice?";
break;
default:
DECS_URL = "";
}
return DECS_URL;
}
}
AuthService:
package com.ssj.baiduapi.xaingmu.config;
import com.alibaba.fastjson.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 更新为你注册的apikey
String clientId = "*****";
// 官网获取的 Secret Key 更新为你注册的Secret Key
String clientSecret = "*****";
return getAuth(clientId, clientSecret);
}
/**
* 获取API访问token 该token有一定的有效期,token要自行管理,当失效时需要重新获取.
*
* @param ak
* - 百度云官网获取的 API Key
* @param sk
* - 百度云官网获取的 Securet Key
* @return assess_token 示例
* "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
*/
private static String getAuth(String ak, String sk) {
// 获取token地址
String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
String getAccessTokenUrl = authHost
// 1. grant_type为固定参敄1¤7
+ "grant_type=client_credentials"
// 2. 官网获取的 API Key
+ "&client_id=" + ak
// 3. 官网获取的 Secret Key
+ "&client_secret=" + sk;
try {
URL realUrl = new URL(getAccessTokenUrl);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
// 获取响应头字段
Map> map = connection.getHeaderFields();
// 遍历响应头
for (String key : map.keySet()) {
System.err.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
/**
* 返回结果示例
*/
System.err.println("result:" + result);
JSONObject jsonObject = JSONObject.parseObject(result.toString());
return jsonObject.getString("access_token");
} catch (Exception e) {
System.err.printf("获取token失败");
e.printStackTrace(System.err);
}
return null;
}
}
Currency:
package com.ssj.baiduapi.xaingmu.config;
import com.ssj.baiduapi.config.BaseImg64;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class Currency {
public static String checkFile(String path,String token) throws URISyntaxException, IOException {
File file = new File(path);
if (!file.exists()) {
throw new NullPointerException("未找到图片");
}
String image = BaseImg64.getImageStrFromPath(path);
String param = "image=" + image;
return post(param,token);
}
private static String post(String param,String token) throws URISyntaxException, IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost();
URI url = new URI(token);
post.setURI(url);
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
StringEntity entity = new StringEntity(param);
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
System.out.println(response.toString());
if (response.getStatusLine().getStatusCode() == 200) {
String str;
try {
str = EntityUtils.toString(response.getEntity());
return str;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return null;
}
}
文字识别同理,修改参数即可