java call OCR Interface Tencent identity document instances (absolutely available)

1. scenario demonstrates

  By reading the information on the ID card photos, automatic filling function. 

2. Analysis

  Want to resolve the relevant information carried on photos, you need to identify the function of the photo, Tencent provides free ID card OCR interface for everyone to use.

  No patient can see a direct interface calls (skip interface rules introduced)

3. interface rules

  Interface Address: https://api.ai.qq.com/fcgi-bin/ocr/ocr_idcardocr

  API Address: https://ai.qq.com/doc/ocridcardocr.shtml

  rule

  note:

  1. retrieval request mode interface must be submitted using the form form, JSON interface to request the transfer of invalid (I've tried);

  2. returns JSON-formatted string, specific data is parsed, and the value can not be directly used as json objects need to first convert it into JSON object.

  Introduction to the Senate

  app_id, uniquely identifies automatically generated after the registered account, with the keys in order to have permission retrieval interface;

  TIME_STAMP, time stamp, the system acquires the current timestamp (in seconds, not milliseconds), check for a timeout (5 minutes);

  nonce_str, random string, the maximum length is 32 bits, we can directly generate 32-bit.

  Sign, for security verification, mainly to prevent data from being tampered during transmission of;

  image, converting the picture into base64 code, only supports picture jpg, png and bmp format and image size can not exceed 1MB.

  Further, not contain picture type declaration, namely: the required head, "data: image / jpeg; base64,", "data: image / png; base64,", "data: image / bmp; base64," removed .

  card_type, very simple, with a 0 if it is positive, negative with 1.

  It should be noted that: app_id, value time_stamp and card_type these three fields is actually a string, ignore the instructions for integer, its value type itself could not simply limit, because it requires that the form must be a form submit the data type of form submission form, it is always only one, that is a string, that they are self-contradictory!

  sign generation rule as follows:


  This means that: these several parameters necessary, after exclusion Sign, lexicographic ascending order (ASCII ascending order), the composition in the form of stitching get request url parameter,

  Results 1. splicing ascending necessary parameters: app_id = value1 & card_type = value2 & image = value3 & nonce_str = value4 & sign = value5 & time_stamp = value6

  2.image value, i.e., the data format required URL base64 encoded values ​​for the remaining fields without using URL encoding.

  3. Generate unencrypted before the string: The results of the first step of splicing the end thereof on the keys, namely: app_id = value1 & card_type = value2 & image = value3 & nonce_str = value4 & sign = value5 & time_stamp = value6 & app_key = value7

  4. Generate sign: the results of the third step, the use of MD5 encryption, encryption result turn uppercase sign of the value obtained.

  Return data

  Value limits (QPS- callable number of requests per second) 

4. Specific call

  Premise: Suppose we pass over to the front is a base64 format images.

  Set constants

// assigned to the interface ID 
Private TX_APP_ID Final static int = 1111111111; 
// key corresponding to the interface 
Private TX_APP_KEY Final static String = "2222222222222222"; 
// address of the interface retrieved 
private final static String TX_ORCURL = "https : // api. ai.qq.com/fcgi-bin/ocr/ocr_idcardocr ";  

  Importing

import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;  

  Specific code

String imgBase64 = request.getParameter("imgBase64");
if (imgBase64.startsWith("data:image/jpeg;base64,")) {
    imgBase64 = imgBase64.replace("data:image/jpeg;base64,", "");
} else if (imgBase64.startsWith("data:image/png;base64,")) {
    imgBase64 = imgBase64.replace("data:image/png;base64,", "");
} else if (imgBase64.startsWith("data:image/bmp;base64,")) {
    imgBase64 = imgBase64.replace("data:image/bmp;base64,", "");
}

// 时间戳
int time_stamp = (int) (System.currentTimeMillis()/1000);
// 随机字符串
String nonce_str = UUID.randomUUID().toString().replace("-", "");
String image = imgBase64;
// Base64 picture
String Sign = "";
// Authentication
// String image = URLEncoder.encode(imgBase64, "UTF-8"); 
// ID card front and back (0- positive; 1- negative) 
int CARD_TYPE = 0; 
// must use TreeMap (automatically generates ordered the Map) 
the Map <String, String> = SortedMap new new TreeMap <> ( ); 
sortedMap.put ( "APP_ID", String.valueOf (TX_APP_ID)); 
sortedMap.put ( "TIME_STAMP", String.valueOf (TIME_STAMP)); 
sortedMap.put ( "nonce_str", nonce_str); 
sortedMap.put ( " Image ", Image); 
sortedMap.put (" CARD_TYPE ", String.valueOf (CARD_TYPE)); 
// generate authentication 
Sign = generateSign (SortedMap); 
sortedMap.put (" Sign ", Sign); 
// retrieval Tencent Interface 
String resultData = httpPostWithForm (TX_ORCURL, SortedMap); 
// resultData further processing of the TODO (returnable directly to the front-end processing)  

  Generating an authentication code for

  Need to import

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.codec.digest.DigestUtils;
/ ** 
 * Tencent generated authentication ID OCR 
 * @explain VALUE1 & key1 = key2 = value2 & ... 
 * @param SortedMap Key in ascending order according to the dictionary the Map 
 * @return Sign (the MD5 encrypted and transferred uppercase) 
 * / 
Private static String generateSign (the Map <String, String> SortedMap) { 
    // authentication 
    String Sign = ""; 
    the Iterator <String> = sortedMap.keySet ITER () Iterator ();. 
    the StringBuilder the StringBuilder new new SB = (); 
    the while (iter.hasNext ()) { 
        String Key = iter.next (); 
        Object value = sortedMap.get (Key); 
        // URL required Base64 encoded 
        IF (key.equals ( "Image")) { 
            the try { 
                value = the URLEncoder.encode (sortedMap.get (key), "UTF -8");
            The catch} (UnsupportedEncodingException E) { 
                E.printStackTrace ();
            } 
        } 
        Sb.append (Key) .append ( "=") the append (value) .append ( "&");. 
    }   
    .. Sb.append ( "app_key") the append ( "=") the append (TX_APP_KEY); 
    // encrypted before 
    sign = sb.toString (); 
    // after encryption (MD5 encrypted and transferred uppercase) 
    Sign = DigestUtils.md5Hex (Sign) .toUpperCase (); 
    return Sign; 
}

  Sending post request code

  Need to import

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/ ** 
 * submitted form form form data, sending post request 
 * @explain 
 * 1. request header: httppost.setHeader ( "the Content-the Type", "file application / X-WWW-form-urlencoded") 
 * 2. submitted data format: & VALUE1 key1 = key2 = value2 ... 
 * @param request URL address 
 * @param paramsMap specific data 
 * @return server returns data 
 * / 
public static String httpPostWithForm (String URL, the Map <String, String> paramsMap) { 
    // results for receiving the return 
    String resultData = ""; 
     the try { 
            HttpPost = POST new new HttpPost (URL); 
            List <BasicNameValuePair> = new new pairList the ArrayList <BasicNameValuePair> (); 
            // iteration Map -> remove key, value into BasicNameValuePair object -> Add to the list 
            for (String key: paramsMap.keySet()) {
                pairList.add (new new BasicNameValuePair (Key, paramsMap.get (Key))); 
            } 
            UrlEncodedFormEntity uefe = new new UrlEncodedFormEntity (pairList, "UTF-. 8"); 
            post.setEntity (uefe); 
            // Create a http client 
            CloseableHttpClient httpClient . = HttpClientBuilder.create () Build (); 
            // send a post request 
            the HttpResponse httpClient.execute Response = (post); 
            
            // status code: 200 is 
            IF (response.getStatusLine () getStatusCode () == HttpStatus.SC_OK.) { 
                // return data: 
                resultData = EntityUtils.toString (response.getEntity (), "UTF-. 8"); 
            } the else {
                throw new RuntimeException ( "Interface connection failed!"); 
            } 
        } the catch (Exception E) { 
            throw new RuntimeException ( "Interface connection failed!"); 
        } 
     return resultData; 
}

  

  

  

 

Written in the last

  Which big brother If it is found there is leakage of the carelessness of the article or need to add more content, welcome message! ! !

 related suggestion:

 

Guess you like

Origin www.cnblogs.com/Marydon20170307/p/11448975.html