mitao
2024-03-14 717811c825b998c3001ad0145bd1fd8f46d1a796
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package com.ruoyi.web.controller.tool;
 
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
 
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
 
/**
 * 百度文字识别
 */
@Slf4j
public class BaiDuApi {
 
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
 
    public static void main(String []args) throws IOException{
//        String url = "C:\\Users\\Admin\\Desktop\\picture\\6fd629ac-3327-4bdc-9459-fcb5295384bc.jpg";
        String url = "C:\\Users\\Admin\\Desktop\\picture\\6fd629ac-3327-4bdc-9459-fcb5295384bc.jpg";
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "image="+getFileContentAsBase64(url,true));
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token="+getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
 
//        System.err.println(response.body().string());
 
        Map<String,Object> map = new HashMap<>();
        String string = response.body().string();
        String idCard = string.substring(string.lastIndexOf("单号:") + 3, string.lastIndexOf("单号:") + 27);
        String time = string.substring(string.lastIndexOf("零时起") + 3, string.lastIndexOf("二十四时")-1);
        time = time.replace(".","-");
        map.put("idCard",idCard);
        map.put("time",time);
        System.err.println(map);
    }
 
    /**
     * 资质证明证件识别
     * @param url
     * @return
     * @throws IOException
     */
    public static Map<String,Object> qualification(String url) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "image="+getFileContentAsBase64(url,true));
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token="+getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        Map<String,Object> map = new HashMap<>();
        try{
            String string = response.body().string();
            String idCard = string.substring(string.lastIndexOf("号:") + 2, string.lastIndexOf("号:") + 21);
            String time = string.substring(string.lastIndexOf("至") + 1, string.lastIndexOf("至") + 11);
            time = time.replace(".","-");
            map.put("idCard",idCard);
            map.put("time",time);
        }catch (Exception e){
            log.error("资质证明证件识别错误!");
            throw new ServiceException("资质证明证件识别错误!");
        }
        return map;
    }
 
    /**
     * 身份证识别
     * @param url
     * @return
     * @throws IOException
     */
    public static Map<String,Object> idCard(String url) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "image="+getFileContentAsBase64(url,true));
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token="+getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        Map<String,Object> map = new HashMap<>();
        try{
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            JSONArray jsonArray = JSONObject.parseArray(jsonObject.getString("words_result"));
            JSONObject obj1 = JSONObject.parseObject(jsonArray.get(0).toString());
            String name = obj1.getString("words");
            name = name.substring(2);
 
            JSONObject obj2 = JSONObject.parseObject(jsonArray.get(1).toString());
            String sexStr = obj2.getString("words");
            sexStr = sexStr.substring(2, 3);
            int sex = "男".equals(sexStr)?0:1;
 
            JSONObject obj3 = JSONObject.parseObject(jsonArray.get(3).toString());
            JSONObject obj4 = JSONObject.parseObject(jsonArray.get(4).toString());
            String address = obj3.getString("words") + obj4.getString("words");
            address = address.substring(2);
 
            JSONObject obj5 = JSONObject.parseObject(jsonArray.get(5).toString());
            String idCard = obj5.getString("words");
            idCard = idCard.substring(6);
 
            map.put("name",name);
            map.put("sex",sex);
            map.put("address",address);
            map.put("idCard",idCard);
        }catch (Exception e){
            log.error("身份证件识别错误!");
            throw new ServiceException("身份证件识别错误!");
        }
        return map;
    }
 
    /**
     * 通用文字识别(标准版)
     * @param url
     * @return
     * @throws IOException
     */
    public static JSONObject pictureOcr(String url) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "image="+getFileContentAsBase64(url,true));
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token="+getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return JSONObject.parseObject(response.body().string());
    }
 
    public static String getAccessToken() 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=2RkKEqd0ltIHPvnIf3G0VpHE&client_secret=RBpPt3O64e3e4BK7pG3lP0o8I6SGgiUy&grant_type=client_credentials")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        JSONObject jsonObject = JSONObject.parseObject(response.body().string());
        return jsonObject.getString("access_token");
    }
 
    /**
     * 获取文件base64编码
     *
     * @param path      文件路径
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息,不带文件头
     * @throws IOException IO异常
     */
    static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
        byte[] b = Files.readAllBytes(Paths.get(path));
        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }
    
}