Yytan-BK

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

统计

完成版,编写实体类和自动生成类

实体类

环境配置:.net Fromework4.0 +Newtonsoft.Json_4.5

using System;
using System.Collections.Generic;
using System.Data;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Newtonsoft.Json;

namespace ConsoleApp
{
    public class DataItem
    {
        public double STKID { get; set; }
        public double SPID { get; set; }
        public string STKNAME { get; set; }
        public string CNAME { get; set; }
    }

    public class RootObject
    {
        public string statusCode { get; set; }
        public string message { get; set; }
        public List<DataItem> data { get; set; }
        public int PsessionID { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //string apiUrl = "http://www.kuaidi100.com/query?type=yuantong&postid=11111111111";
            string apiUrl = "https://bff.gds.org.cn/gds/searching-api/ProductService/ProductListByGTIN?PageSize=30&PageIndex=1&SearchItem=06902952880294";
            //string apiUrl = "http://baike.baidu.com/api/openapi/BaikeLemmaCardApi?scope=103&format=json&appid=379020&bk_key=%E9%93%B6%E9%AD%82&bk_length=600";
            DataTable dataTable = CallApiAndConvertToDataTable(apiUrl);

            if (dataTable != null)
            {
                // 打印 DataTable 中的数据
                foreach (DataRow row in dataTable.Rows)
                {
                    Console.WriteLine("成功");
                }
            }
            Console.ReadLine();
        }
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)

        {

            return true;

        }
        static DataTable CallApiAndConvertToDataTable(string apiUrl)
        {
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);

            // 重點是修改這行
            

            ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; // SecurityProtocolType.Tls1.2
            using (WebClient client = new WebClient())
            {
                client.Encoding = Encoding.UTF8; // 设置编码为 UTF-8
                client.Credentials = CredentialCache.DefaultCredentials;
                client.Headers.Add("User-Agent", "Microsoft Internet Explorer");
                client.Headers.Add("Host", "www.gds.org.cn");

                try
                {
                    var jsonData = client.DownloadData(apiUrl);
                    var jsonResponse = Encoding.UTF8.GetString(jsonData); // 将字节数组转换为字符串

                    RootObject root = JsonConvert.DeserializeObject<RootObject>(jsonResponse);

                    DataTable dataTable = CreateDataTable();

                    foreach (var dataItem in root.data)
                    {
                        DataRow row = dataTable.NewRow();
                        row["STKID"] = dataItem.STKID;
                        row["SPID"] = dataItem.SPID;
                        row["STKNAME"] = dataItem.STKNAME;
                        row["CNAME"] = dataItem.CNAME;
                        dataTable.Rows.Add(row);
                    }

                    return dataTable;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("发生错误:" + ex.Message);
                    return null;
                }
            }
        }
        static DataTable CreateDataTable()
        {
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("STKID", typeof(double));
            dataTable.Columns.Add("SPID", typeof(double));
            dataTable.Columns.Add("STKNAME", typeof(string));
            dataTable.Columns.Add("CNAME", typeof(string));
            return dataTable;
        }
    }
}

自动生成类

using System;
using System.Data;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Newtonsoft.Json.Linq;

namespace ConsoleApp
{

    class Program
    {
        static void Main(string[] args)
        {
            string apiUrl = "https://bff.gds.org.cn/gds/searching-api/ProductService/ProductListByGTIN?PageSize=30&PageIndex=1&SearchItem=06902952880294"; // 替换为实际的 API URL
            string jsonResponse = CallApi(apiUrl);

            if (!string.IsNullOrEmpty(jsonResponse))
            {
                DataTable dataTable = CreateDataTable();

                JObject jsonData = JObject.Parse(jsonResponse);
                JArray items = jsonData["Data"]["Items"] as JArray;

                foreach (JObject item in items)
                {
                    DataRow row = dataTable.NewRow();
                    row["keyword"] = item["keyword"].ToString();
                    row["branch_code"] = item["branch_code"].ToString();
                    row["brandid"] = item["brandid"].ToString();
                    row["brandcn"] = item["brandcn"].ToString();
                    row["code"] = item["code"].ToString();
                    row["valid_date"] = item["valid_date"].ToString();
                    row["logout_date"] = item["logout_date"]?.ToString();
                    dataTable.Rows.Add(row);
                }
                Console.ReadLine();

            }
        }
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }
        //查看链接是否正常
        static string CallApi(string apiUrl)
        {
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
            using (WebClient client = new WebClient())
            {
                client.Encoding = Encoding.UTF8; // 设置编码为 UTF-8
                client.Credentials = CredentialCache.DefaultCredentials;
                client.Headers.Add("User-Agent", "Microsoft Internet Explorer");
                client.Headers.Add("Host", "www.gds.org.cn");
                try
                {
                    var jsonData = client.DownloadData(apiUrl);
                    var jsonResponse = Encoding.UTF8.GetString(jsonData);
                    return jsonResponse; 
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");
                    return null;
                }
            }
        }

        static DataTable CreateDataTable()
        {
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("keyword");
            dataTable.Columns.Add("branch_code");
            dataTable.Columns.Add("brandid");
            dataTable.Columns.Add("brandcn");
            dataTable.Columns.Add("code");
            dataTable.Columns.Add("valid_date");
            dataTable.Columns.Add("logout_date");
            return dataTable;
        }
    }
}

 

posted on   孤幽影暗  阅读(21)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示