首页 条码生成识别 条码生成识别示例代码 条码识别[C#]

条码识别示例代码C#

作者: 阅读数:1129 上传时间:2025-05-26

条码识别

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

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

    public static async Task ReadAsync(string barcode)
    {
        try
        {
            // 构建读取条形码的请求 URL
            string url = $"https://api.jisuapi.com/barcode/read?appkey={AppKey}&barcode={barcode}";

            using (HttpClient client = new HttpClient())
            {
                // 发送 GET 请求
                HttpResponseMessage response = await client.GetAsync(url);
                // 确保请求成功
                response.EnsureSuccessStatusCode();

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

                // 检查状态码
                if (jsonarr["status"] != null && (int)jsonarr["status"] != 0)
                {
                    if (jsonarr["msg"] != null)
                    {
                        Console.WriteLine(jsonarr["msg"]);
                    }
                    return;
                }

                // 获取结果数组
                JArray result = (JArray)jsonarr["result"];
                if (result != null)
                {
                    // 遍历结果数组
                    foreach (JObject val in result)
                    {
                        Console.WriteLine($"{val["type"]} {val["number"]}");
                    }
                }
            }
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine($"请求出错: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"发生错误: {ex.Message}");
        }
    }
	
	public static async Task Main()
    {
        // 读取条形码
        await Barcode.ReadAsync("https://api.jisuapi.com/barcode/barcode/1471602033673149.png");
    }
}