开发示例

识别 接口 调用 说明

  • 识别服务调用主要分为三个步骤:
  • 1)将客户端文件读成二进制流,转换成base64编码。
  • 2)调用http识别服务API获取卡片信息。
  • 3)对识别结果进行处理(写入数据库,或者前端浏览等)。
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.apache.commons.codec.binary.Base64;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Demo1 {
	public static void main(String[] args) throws IOException   {
		
		OkHttpClient client = new OkHttpClient.Builder()
			.connectTimeout(15, TimeUnit.SECONDS)// 连接超时(单位:秒)
			.writeTimeout(30, TimeUnit.SECONDS)// 写入超时(单位:秒)
			.readTimeout(60, TimeUnit.SECONDS)// 读取超时(单位:秒)
			.build();
 		InputStream in = new FileInputStream("G:\\\\证件识别\\20140610_115032.jpg");
		byte[] data = null;
		try {
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 对字节数组Base64编码
		Base64 encoder = new Base64();
 
		String fileData = encoder.encodeToString(data);

		FormBody mBody = new FormBody.Builder()
				.add("key", "VmgdozifBxpJ5zxCvS7RhU")
				.add("secret", "0360218d3a8f4ac9ae0774801f21c574")
				.add("pid", "2")
				.add("file", fileData)
				.build();

		URL realUrl = new URL("http://localhost:8080/api/recog.srvc");
		Request request = new Request.Builder().url( realUrl).post(mBody).build();
		
		Response response = client.newCall(request).execute();

		System.out.println( response.body().string() );
	}

}	
	
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;

namespace OcrDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream fs = File.OpenRead(@"G:\\证件识别\20170816194322873.jpg");
            byte[] arr = new byte[fs.Length];
            fs.Read(arr, 0, (int)fs.Length);
            String fileData = Convert.ToBase64String(arr);

            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.None };
            Uri uri = new Uri("http://localhost:8080/api/recog.srvc");

            using (var httpClient = new HttpClient(handler))
            {
                httpClient.DefaultRequestHeaders.Add("Method", "Post");
                Dictionary dict = new Dictionary()
                {
                   {"key", "VmgdozifBxpJ5zxCvS7RhU"},
                   {"secret", "0360218d3a8f4ac9ae0774801f21c574" },
                   {"pid", "2"  },
                   { "file", HttpUtility.UrlEncode(fileData, Encoding.UTF8)}
                };
                StringBuilder stringBuilder = new StringBuilder();
                foreach (KeyValuePair nameValue in dict)
                {
                    if (stringBuilder.Length > 0)
                        stringBuilder.Append('&');
                    stringBuilder.Append(nameValue.Key);
                    stringBuilder.Append('=');
                    stringBuilder.Append(nameValue.Value);
                };

                StringContent content = new StringContent(stringBuilder.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded");
                
                HttpResponseMessage response = httpClient.PostAsync(uri, content).Result;
                
                //确保HTTP成功状态值
                response.EnsureSuccessStatusCode();
                Console.WriteLine( response.Content.ReadAsStringAsync().Result);
            }

            

            Console.ReadKey(); 
        }
    }
}
    
function base64EncodeImage ($image_file) {
    $base64_image = '';
    $image_info = getimagesize($image_file);
    $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
    $base64_image = chunk_split(base64_encode($image_data));
    return $base64_image;
}

function OCRDemo($filepath) {
    $filepath = realpath ( $filepath );
    //$filepage = "20170816194322873.jpg";
    $base64_img = base64EncodeImage($filepath);

    $file = array (
        "key" => "VmgdozifBxpJ5zxCvS7RhU",
        "secret" => "0360218d3a8f4ac9ae0774801f21c574",
        "pid" => "2",
        "file" => $base64_img
    );

    $curl = curl_init();
    curl_setopt ( $curl, CURLOPT_URL, "http://localhost:8080/api/recog.srvc" );
    curl_setopt ( $curl, CURLOPT_POST, true );
    curl_setopt ( $curl, CURLOPT_POSTFIELDS, $file );
    curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, true );
    $result = curl_exec ( $curl );

    curl_close ( $curl );
    return json_decode ( $result, true );
}

print_r( OCRDemo('20170816194322873.jpg'));