springboot項目集成百度api:
實現證件及票據識別.
項目結構:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ssj</groupId>
<artifactId>baiduapi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>baiduapi</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</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>
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.12</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
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<String, List<String>> 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;
}
}
文字識別同理,修改參數即可