首页 身份证识别 身份证识别示例代码 获取识别类型[C#]

获取识别类型示例代码C#

作者: 阅读数:1128 上传时间:2025-04-23

获取识别类型

using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

class IdCardRecognition
{
    // 替换成你的AppKey
    private const string AppKey = "YOUR_APPKEY_HERE";

    public static async Task RecognizeAsync(string imagePath)
    {
        try
        {
            using (HttpClient client = new HttpClient())
            {
                // 读取图片并进行 Base64 编码
                byte[] imageBytes = File.ReadAllBytes(imagePath);
                string base64Image = Convert.ToBase64String(imageBytes);

                // 构建请求数据
                var formData = new MultipartFormDataContent();
                formData.Add(new StringContent(AppKey), "appkey");
                formData.Add(new StringContent("2"), "typeid");
                formData.Add(new StringContent(base64Image), "pic");

                // 发送 POST 请求
                string url = "https://api.jisuapi.com/idcardrecognition/recognize";
                HttpResponseMessage response = await client.PostAsync(url, formData);
                response.EnsureSuccessStatusCode();

                // 读取响应内容
                string responseBody = await response.Content.ReadAsStringAsync();
                JObject jsonarr = JObject.Parse(responseBody);

                // 处理 API 返回状态
                if ((int)jsonarr["status"] != 0)
                {
                    Console.WriteLine(jsonarr["msg"]);
                    return;
                }

                // 处理识别结果
                JObject result = (JObject)jsonarr["result"];
                foreach (var property in result.Properties())
                {
                    Console.WriteLine($"{property.Name} {property.Value}");
                }
            }
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine($"请求异常:{ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"发生错误:{ex.Message}");
        }
    }
	
	static async Task Main(string[] args)
    {
        // 调用获取证件类型方法
        await IdCardRecognition.TypeAsync();

        // 调用识别身份证图片方法,替换为实际的图片路径
        string imagePath = @"C:\Users\Administrator\Desktop\2.jpg";
        await IdCardRecognition.RecognizeAsync(imagePath);
    }
}