diff --git a/ruoyi-admin/pom.xml b/ruoyi-admin/pom.xml index 9a4cde8f..6724af40 100644 --- a/ruoyi-admin/pom.xml +++ b/ruoyi-admin/pom.xml @@ -61,6 +61,58 @@ ruoyi-generator + + + com.baidu.aip + java-sdk + 4.16.10 + + + + org.netbeans.external + com-google-gson + RELEASE113 + + + + com.squareup.okhttp3 + okhttp + 4.9.3 + + + + + + com.alibaba + fastjson + 1.2.78 + + + + org.apache.httpcomponents + httpclient + 4.2.1 + + + org.apache.httpcomponents + httpcore + 4.2.1 + + + commons-lang + commons-lang + 2.6 + + + + junit + junit + 4.5 + test + + + + diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/ali/HttpUtils.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/ali/HttpUtils.java new file mode 100644 index 00000000..272adfc8 --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/ali/HttpUtils.java @@ -0,0 +1,314 @@ +package com.ruoyi.web.controller.app.ali; + +//package com.aliyun.api.gateway.demo.util; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import org.apache.commons.lang.StringUtils; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.HttpClient; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.entity.ByteArrayEntity; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.message.BasicNameValuePair; + +public class HttpUtils { + + /** + * get + * + * @param host + * @param path + * @param method + * @param headers + * @param querys + * @return + * @throws Exception + */ + public static HttpResponse doGet(String host, String path, String method, + Map headers, + Map querys) + throws Exception { + HttpClient httpClient = wrapClient(host); + + HttpGet request = new HttpGet(buildUrl(host, path, querys)); + for (Map.Entry e : headers.entrySet()) { + request.addHeader(e.getKey(), e.getValue()); + } + + return httpClient.execute(request); + } + + /** + * post form + * + * @param host + * @param path + * @param method + * @param headers + * @param querys + * @param bodys + * @return + * @throws Exception + */ + public static HttpResponse doPost(String host, String path, String method, + Map headers, + Map querys, + Map bodys) + throws Exception { + HttpClient httpClient = wrapClient(host); + + HttpPost request = new HttpPost(buildUrl(host, path, querys)); + for (Map.Entry e : headers.entrySet()) { + request.addHeader(e.getKey(), e.getValue()); + } + + if (bodys != null) { + List nameValuePairList = new ArrayList(); + + for (String key : bodys.keySet()) { + nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key))); + } + UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8"); + formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8"); + request.setEntity(formEntity); + } + + return httpClient.execute(request); + } + + /** + * Post String + * + * @param host + * @param path + * @param method + * @param headers + * @param querys + * @param body + * @return + * @throws Exception + */ + public static HttpResponse doPost(String host, String path, String method, + Map headers, + Map querys, + String body) + throws Exception { + HttpClient httpClient = wrapClient(host); + + HttpPost request = new HttpPost(buildUrl(host, path, querys)); + for (Map.Entry e : headers.entrySet()) { + request.addHeader(e.getKey(), e.getValue()); + } + + if (StringUtils.isNotBlank(body)) { + request.setEntity(new StringEntity(body, "utf-8")); + } + + return httpClient.execute(request); + } + + /** + * Post stream + * + * @param host + * @param path + * @param method + * @param headers + * @param querys + * @param body + * @return + * @throws Exception + */ + public static HttpResponse doPost(String host, String path, String method, + Map headers, + Map querys, + byte[] body) + throws Exception { + HttpClient httpClient = wrapClient(host); + + HttpPost request = new HttpPost(buildUrl(host, path, querys)); + for (Map.Entry e : headers.entrySet()) { + request.addHeader(e.getKey(), e.getValue()); + } + + if (body != null) { + request.setEntity(new ByteArrayEntity(body)); + } + + return httpClient.execute(request); + } + + /** + * Put String + * @param host + * @param path + * @param method + * @param headers + * @param querys + * @param body + * @return + * @throws Exception + */ + public static HttpResponse doPut(String host, String path, String method, + Map headers, + Map querys, + String body) + throws Exception { + HttpClient httpClient = wrapClient(host); + + HttpPut request = new HttpPut(buildUrl(host, path, querys)); + for (Map.Entry e : headers.entrySet()) { + request.addHeader(e.getKey(), e.getValue()); + } + + if (StringUtils.isNotBlank(body)) { + request.setEntity(new StringEntity(body, "utf-8")); + } + + return httpClient.execute(request); + } + + /** + * Put stream + * @param host + * @param path + * @param method + * @param headers + * @param querys + * @param body + * @return + * @throws Exception + */ + public static HttpResponse doPut(String host, String path, String method, + Map headers, + Map querys, + byte[] body) + throws Exception { + HttpClient httpClient = wrapClient(host); + + HttpPut request = new HttpPut(buildUrl(host, path, querys)); + for (Map.Entry e : headers.entrySet()) { + request.addHeader(e.getKey(), e.getValue()); + } + + if (body != null) { + request.setEntity(new ByteArrayEntity(body)); + } + + return httpClient.execute(request); + } + + /** + * Delete + * + * @param host + * @param path + * @param method + * @param headers + * @param querys + * @return + * @throws Exception + */ + public static HttpResponse doDelete(String host, String path, String method, + Map headers, + Map querys) + throws Exception { + HttpClient httpClient = wrapClient(host); + + HttpDelete request = new HttpDelete(buildUrl(host, path, querys)); + for (Map.Entry e : headers.entrySet()) { + request.addHeader(e.getKey(), e.getValue()); + } + + return httpClient.execute(request); + } + + private static String buildUrl(String host, String path, Map querys) throws UnsupportedEncodingException { + StringBuilder sbUrl = new StringBuilder(); + sbUrl.append(host); + if (!StringUtils.isBlank(path)) { + sbUrl.append(path); + } + if (null != querys) { + StringBuilder sbQuery = new StringBuilder(); + for (Map.Entry query : querys.entrySet()) { + if (0 < sbQuery.length()) { + sbQuery.append("&"); + } + if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) { + sbQuery.append(query.getValue()); + } + if (!StringUtils.isBlank(query.getKey())) { + sbQuery.append(query.getKey()); + if (!StringUtils.isBlank(query.getValue())) { + sbQuery.append("="); + sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8")); + } + } + } + if (0 < sbQuery.length()) { + sbUrl.append("?").append(sbQuery); + } + } + + return sbUrl.toString(); + } + + private static HttpClient wrapClient(String host) { + HttpClient httpClient = new DefaultHttpClient(); + if (host.startsWith("https://")) { + sslClient(httpClient); + } + + return httpClient; + } + + private static void sslClient(HttpClient httpClient) { + try { + SSLContext ctx = SSLContext.getInstance("TLS"); + X509TrustManager tm = new X509TrustManager() { + public X509Certificate[] getAcceptedIssuers() { + return null; + } + public void checkClientTrusted(X509Certificate[] xcs, String str) { + + } + public void checkServerTrusted(X509Certificate[] xcs, String str) { + + } + }; + ctx.init(null, new TrustManager[] { tm }, null); + SSLSocketFactory ssf = new SSLSocketFactory(ctx); + ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + ClientConnectionManager ccm = httpClient.getConnectionManager(); + SchemeRegistry registry = ccm.getSchemeRegistry(); + registry.register(new Scheme("https", 443, ssf)); + } catch (KeyManagementException ex) { + throw new RuntimeException(ex); + } catch (NoSuchAlgorithmException ex) { + throw new RuntimeException(ex); + } + } +} \ No newline at end of file diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/ali/OcrIdCardALI.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/ali/OcrIdCardALI.java new file mode 100644 index 00000000..f86c1f8b --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/ali/OcrIdCardALI.java @@ -0,0 +1,169 @@ +package com.ruoyi.web.controller.app.ali; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import org.apache.http.HttpResponse; +import org.apache.http.util.EntityUtils; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import org.apache.commons.codec.binary.Base64; + +public class OcrIdCardALI { + public static String img_base64(String path) { + /** + * 对path进行判断,如果是本地文件就二进制读取并base64编码,如果是url,则返回 + */ + String imgBase64=""; + if (path.startsWith("http")){ + imgBase64 = path; + }else { + try { + File file = new File(path); + byte[] content = new byte[(int) file.length()]; + FileInputStream finputstream = new FileInputStream(file); + finputstream.read(content); + finputstream.close(); + imgBase64 = new String(Base64.encodeBase64(content)); + } catch (IOException e) { + e.printStackTrace(); + return imgBase64; + } + } + + return imgBase64; + } + public static String get_id_card_info(String imgFile, String side, boolean quality_info) { + + String host = "https://cardnumber.market.alicloudapi.com"; + String path = "/rest/160601/ocr/ocr_idcard.json"; + String appcode = "f294b9cfd4124feda0bdcb6d10c0c259"; + + String method = "POST"; + + Map headers = new HashMap(); + //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105 + headers.put("Authorization", "APPCODE " + appcode); + //根据API的要求,定义相对应的Content-Type + headers.put("Content-Type", "application/json; charset=UTF-8"); + + Map querys = new HashMap(); + // 对图像进行base64编码 + String imgBase64 = img_base64(imgFile); + + //configure配置 + JSONObject configObj = new JSONObject(); + configObj.put("side", side); + // 判断图像质量 + configObj.put("quality_info", quality_info); + + String config_str = configObj.toString(); + + // 拼装请求body的json字符串 + JSONObject requestObj = new JSONObject(); + requestObj.put("image", imgBase64); + if(configObj.size() > 0) { + requestObj.put("configure", config_str); + } + String bodys = requestObj.toString(); + + try { + /** + * 重要提示如下: + * HttpUtils请从 + * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java + * 下载 + * + * 相应的依赖请参照,必须使用这个依赖中的版本。。。。。。。。。。。 + * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml + */ + HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys); + int stat = response.getStatusLine().getStatusCode(); + if(stat != 200){ + System.out.println("Http code: " + stat); + System.out.println("http header error msg: "+ response.getFirstHeader("X-Ca-Error-Message")); + System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity())); + return "false"; + } + + String res = EntityUtils.toString(response.getEntity()); + JSONObject res_obj = JSON.parseObject(res); + + //测试实名认证效果 + System.out.println(res_obj.toJSONString()); + + return res_obj.toJSONString(); + + + } catch (Exception e) { + e.printStackTrace(); + return "false"; + } + + + + } + + public static void main(String[] args) { + String host = "https://cardnumber.market.alicloudapi.com"; + String path = "/rest/160601/ocr/ocr_idcard.json"; + String appcode = "f294b9cfd4124feda0bdcb6d10c0c259"; + String imgFile = "C:\\Users\\admin\\Pictures\\Camera Roll\\身份证face.jpg"; + String method = "POST"; + + Map headers = new HashMap(); + //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105 + headers.put("Authorization", "APPCODE " + appcode); + //根据API的要求,定义相对应的Content-Type + headers.put("Content-Type", "application/json; charset=UTF-8"); + + Map querys = new HashMap(); + // 对图像进行base64编码 + String imgBase64 = img_base64(imgFile); + + //configure配置 + JSONObject configObj = new JSONObject(); + configObj.put("side", "face"); + // 判断图像质量 + configObj.put("quality_info",true); + + String config_str = configObj.toString(); + + // 拼装请求body的json字符串 + JSONObject requestObj = new JSONObject(); + requestObj.put("image", imgBase64); + if(configObj.size() > 0) { + requestObj.put("configure", config_str); + } + String bodys = requestObj.toString(); + + try { + /** + * 重要提示如下: + * HttpUtils请从 + * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java + * 下载 + * + * 相应的依赖请参照,必须使用这个依赖中的版本。。。。。。。。。。。 + * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml + */ + HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys); + int stat = response.getStatusLine().getStatusCode(); + if(stat != 200){ + System.out.println("Http code: " + stat); + System.out.println("http header error msg: "+ response.getFirstHeader("X-Ca-Error-Message")); + System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity())); + return; + } + + String res = EntityUtils.toString(response.getEntity()); + JSONObject res_obj = JSON.parseObject(res); + + System.out.println(res_obj.toJSONString()); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/baidu/Base64Util.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/baidu/Base64Util.java new file mode 100644 index 00000000..24328add --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/baidu/Base64Util.java @@ -0,0 +1,65 @@ +package com.ruoyi.web.controller.app.baidu; + +/** + * Base64 工具类 + */ +public class Base64Util { + private static final char last2byte = (char) Integer.parseInt("00000011", 2); + private static final char last4byte = (char) Integer.parseInt("00001111", 2); + private static final char last6byte = (char) Integer.parseInt("00111111", 2); + private static final char lead6byte = (char) Integer.parseInt("11111100", 2); + private static final char lead4byte = (char) Integer.parseInt("11110000", 2); + private static final char lead2byte = (char) Integer.parseInt("11000000", 2); + private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; + + public Base64Util() { + } + + public static String encode(byte[] from) { + StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3); + int num = 0; + char currentByte = 0; + + int i; + for (i = 0; i < from.length; ++i) { + for (num %= 8; num < 8; num += 6) { + switch (num) { + case 0: + currentByte = (char) (from[i] & lead6byte); + currentByte = (char) (currentByte >>> 2); + case 1: + case 3: + case 5: + default: + break; + case 2: + currentByte = (char) (from[i] & last6byte); + break; + case 4: + currentByte = (char) (from[i] & last4byte); + currentByte = (char) (currentByte << 2); + if (i + 1 < from.length) { + currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6); + } + break; + case 6: + currentByte = (char) (from[i] & last2byte); + currentByte = (char) (currentByte << 4); + if (i + 1 < from.length) { + currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4); + } + } + + to.append(encodeTable[currentByte]); + } + } + + if (to.length() % 4 != 0) { + for (i = 4 - to.length() % 4; i > 0; --i) { + to.append("="); + } + } + + return to.toString(); + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/baidu/FileUtil.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/baidu/FileUtil.java new file mode 100644 index 00000000..2584f5ca --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/baidu/FileUtil.java @@ -0,0 +1,72 @@ +package com.ruoyi.web.controller.app.baidu; + +import java.io.*; + +/** + * 文件读取工具类 + */ +public class FileUtil { + + /** + * 读取文件内容,作为字符串返回 + */ + public static String readFileAsString(String filePath) throws IOException { + File file = new File(filePath); + if (!file.exists()) { + throw new FileNotFoundException(filePath); + } + + if (file.length() > 1024 * 1024 * 1024) { + throw new IOException("File is too large"); + } + + StringBuilder sb = new StringBuilder((int) (file.length())); + // 创建字节输入流 + FileInputStream fis = new FileInputStream(filePath); + // 创建一个长度为10240的Buffer + byte[] bbuf = new byte[10240]; + // 用于保存实际读取的字节数 + int hasRead = 0; + while ( (hasRead = fis.read(bbuf)) > 0 ) { + sb.append(new String(bbuf, 0, hasRead)); + } + fis.close(); + return sb.toString(); + } + + /** + * 根据文件路径读取byte[] 数组 + */ + 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) file.length()); + BufferedInputStream in = null; + + try { + in = new BufferedInputStream(new FileInputStream(file)); + short bufSize = 1024; + byte[] buffer = new byte[bufSize]; + int len1; + while (-1 != (len1 = in.read(buffer, 0, bufSize))) { + bos.write(buffer, 0, len1); + } + + byte[] var7 = bos.toByteArray(); + return var7; + } finally { + try { + if (in != null) { + in.close(); + } + } catch (IOException var14) { + var14.printStackTrace(); + } + + bos.close(); + } + } + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/baidu/GetToken.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/baidu/GetToken.java new file mode 100644 index 00000000..ada2d4d7 --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/baidu/GetToken.java @@ -0,0 +1,25 @@ +package com.ruoyi.web.controller.app.baidu; + +import okhttp3.*; +import org.json.JSONObject; + +import java.io.*; + +class GetToken { + + static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build(); + + public static void main(String []args) throws IOException{ + MediaType mediaType = MediaType.parse("application/json"); + RequestBody body = RequestBody.create(mediaType, ""); + Request request = new Request.Builder() + .url("https://aip.baidubce.com/oauth/2.0/token?client_id=G1HsVOPNZhQTe1TyPCPz30kg&client_secret=zKrNsDNe9uEMQLpD5zXzXO4CVwT3spEH&grant_type=client_credentials") + .method("POST", body) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + Response response = HTTP_CLIENT.newCall(request).execute(); + System.out.println(response.body().string()); + + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/baidu/GsonUtils.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/baidu/GsonUtils.java new file mode 100644 index 00000000..bec2b7e6 --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/baidu/GsonUtils.java @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2017 Baidu, Inc. All Rights Reserved. + */ +package com.ruoyi.web.controller.app.baidu; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; + +import java.lang.reflect.Type; + +/** + * Json工具类. + */ +public class GsonUtils { + private static Gson gson = new GsonBuilder().create(); + + public static String toJson(Object value) { + return gson.toJson(value); + } + + public static T fromJson(String json, Class classOfT) throws JsonParseException { + return gson.fromJson(json, classOfT); + } + + public static T fromJson(String json, Type typeOfT) throws JsonParseException { + return (T) gson.fromJson(json, typeOfT); + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/baidu/HttpUtil.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/baidu/HttpUtil.java new file mode 100644 index 00000000..e3c3d560 --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/baidu/HttpUtil.java @@ -0,0 +1,77 @@ +package com.ruoyi.web.controller.app.baidu; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.List; +import java.util.Map; + +/** + * http 工具类 + */ +public class HttpUtil { + + public static String post(String requestUrl, String accessToken, String params) + throws Exception { + String contentType = "application/x-www-form-urlencoded"; + return HttpUtil.post(requestUrl, accessToken, contentType, params); + } + + public static String post(String requestUrl, String accessToken, String contentType, String params) + throws Exception { + String encoding = "UTF-8"; + if (requestUrl.contains("nlp")) { + encoding = "GBK"; + } + return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding); + } + + public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding) + throws Exception { + String url = requestUrl + "?access_token=" + accessToken; + return HttpUtil.postGeneralUrl(url, contentType, params, encoding); + } + + public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding) + throws Exception { + URL url = new URL(generalUrl); + // 打开和URL之间的连接 + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + // 设置通用的请求属性 + connection.setRequestProperty("Content-Type", contentType); + connection.setRequestProperty("Connection", "Keep-Alive"); + connection.setUseCaches(false); + connection.setDoOutput(true); + connection.setDoInput(true); + + // 得到请求的输出流对象 + DataOutputStream out = new DataOutputStream(connection.getOutputStream()); + out.write(params.getBytes(encoding)); + out.flush(); + out.close(); + + // 建立实际的连接 + connection.connect(); + // 获取所有响应头字段 + Map> headers = connection.getHeaderFields(); + // 遍历所有的响应头字段 + for (String key : headers.keySet()) { + System.err.println(key + "--->" + headers.get(key)); + } + // 定义 BufferedReader输入流来读取URL的响应 + BufferedReader in = null; + in = new BufferedReader( + new InputStreamReader(connection.getInputStream(), encoding)); + String result = ""; + String getLine; + while ((getLine = in.readLine()) != null) { + result += getLine; + } + in.close(); + System.err.println("result:" + result); + return result; + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/baidu/OcrIdCardBAI.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/baidu/OcrIdCardBAI.java new file mode 100644 index 00000000..86f73c8e --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/app/baidu/OcrIdCardBAI.java @@ -0,0 +1,72 @@ +package com.ruoyi.web.controller.app.baidu; + +import com.ruoyi.web.controller.app.baidu.Base64Util; +import com.ruoyi.web.controller.app.baidu.FileUtil; +import com.ruoyi.web.controller.app.baidu.HttpUtil; + +import java.net.URLEncoder; + +/** + * 身份证识别 + */ +public class OcrIdCardBAI { + + /** + * 重要提示代码中所需工具类 + * FileUtil,Base64Util,HttpUtil,GsonUtils请从 + * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72 + * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2 + * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3 + * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3 + * 下载 + */ + /* + param: + image:图片路径 + id_card_side:身份证正反面参数,front表示身份证正面,back表示身份证反面 + detect_ps:是否检测Ps,true表示检测,false表示不检测,默认为false + detect_risk:是否检测风险(身份证复印件,临时身份证,身份证反派,修改过的身份证),true表示检测,false表示不检测,默认为false + detect_quality:是否检测图像质量,true表示检测,false表示不检测,默认为false + detect_card:身份证是否进行裁剪返回裁剪后的图片,true表示检测,false表示不检测,默认为false + 参数和返回参数详解 https://cloud.baidu.com/doc/OCR/s/rk3h7xzck + + * */ + public static String idcard(String image, String id_card_side, String detect_ps, String detect_risk, String detect_quality, String detect_card) { + // 请求url + String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard"; + try { + // 本地文件路径 + String filePath = image; + byte[] imgData = FileUtil.readFileByBytes(filePath); + String imgStr = Base64Util.encode(imgData); + String imgParam = URLEncoder.encode(imgStr, "UTF-8"); + + String param = "id_card_side=" + id_card_side + "&detect_ps=" + detect_ps + "&detect_risk=" + detect_risk + "&detect_quality=" + detect_quality + "&detect_card=" + detect_card + "&image=" + imgParam; + + // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。 + // 使用之前要通过GetToken方法获取token, token默认30天有效。 + String accessToken = "24.95d7e343c57fb6adcdbb7510c99ac6eb.2592000.1731637408.282335-115883169"; + + String result = HttpUtil.post(url, accessToken, param); +// System.out.println(result); + return result; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static void main(String[] args) { + String image = "C:\\Users\\admin\\Pictures\\Camera Roll\\haotian_face.jpg"; + String id_card_side = "front"; + String detect_ps = "true"; + String detect_risk = "true"; + String detect_quality = "true"; + String detect_card = "false"; + + String result; + result = OcrIdCardBAI.idcard(image, id_card_side, detect_ps, detect_risk, detect_quality, detect_card); + System.out.println(result); + + } +} \ No newline at end of file