zoukankan      html  css  js  c++  java
  • C# 获取社会统一信用代码

    时间不多,废话少说:

    网络请求代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net.Security;
    using System.Security.Cryptography.X509Certificates;
    using System.DirectoryServices.Protocols;
    using System.ServiceModel.Security;
    using System.Net;
    using System.IO;
    using System.IO.Compression;
    using System.Text.RegularExpressions;
    using System.Threading;
    
    namespace Meeting.Common
    {
        /// <summary>  
        /// 有关HTTP请求的辅助类  
        /// </summary>  
        public class HttpWebResponseUtility
        {
    
            public static string GetUrl(string url)
            {
    
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    System.Console.WriteLine("https connections.....");
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    // 这里设置了协议类型。
                    //ServicePointManager.SecurityProtocol =SecurityProtocolType.Tls12;// (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2; 
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; //(SecurityProtocolType)768 | (SecurityProtocolType)3072
    
                    ServicePointManager.CheckCertificateRevocationList = true;
                    ServicePointManager.DefaultConnectionLimit = 1000;
                    ServicePointManager.Expect100Continue = false;
                }
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                //增加下面两个属性即可  
                request.KeepAlive = false;
                request.ProtocolVersion = HttpVersion.Version10;
    
                request.Method = "GET";    //使用get方式发送数据
                request.ContentType = "application/x-www-form-urlencoded";
                request.Referer = "";
                request.AllowAutoRedirect = true;
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
                request.Accept = "*/*";
    
                //获取网页响应结果
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
               // Thread.Sleep(2000);
                Stream stream = response.GetResponseStream();
                //client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                string result = string.Empty;
                using (StreamReader sr = new StreamReader(stream))
                {
                    result = sr.ReadToEnd();
                }
    
                if (request != null)
                {
                    request.Abort();
                }
    
                if (response != null)
                {
                    response.Close();
                }
    
                return result;
            }
            private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
            /// <summary>  
            /// 创建GET方式的HTTP请求  
            /// </summary>  
            /// <param name="url">请求的URL</param>  
            /// <param name="timeout">请求的超时时间</param>  
            /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>  
            /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>  
            /// <returns></returns>  
            public static HttpWebResponse CreateGetHttpResponse(string url, int? timeout, string userAgent, CookieCollection cookies)
            {
                if (string.IsNullOrEmpty(url))
                {
                    throw new ArgumentNullException("url");
                }
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "GET";
                request.UserAgent = DefaultUserAgent;
                if (!string.IsNullOrEmpty(userAgent))
                {
                    request.UserAgent = userAgent;
                }
                if (timeout.HasValue)
                {
                    request.Timeout = timeout.Value;
                }
                if (cookies != null)
                {
                    request.CookieContainer = new CookieContainer();
                    request.CookieContainer.Add(cookies);
                }
                return request.GetResponse() as HttpWebResponse;
            }
            /// <summary>  
            /// 创建POST方式的HTTP请求  
            /// </summary>  
            /// <param name="url">请求的URL</param>  
            /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>  
            /// <param name="timeout">请求的超时时间</param>  
            /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>  
            /// <param name="requestEncoding">发送HTTP请求时所用的编码</param>  
            /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>  
            /// <returns></returns>  
            public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies)
            {
                if (string.IsNullOrEmpty(url))
                {
                    throw new ArgumentNullException("url");
                }
                if (requestEncoding == null)
                {
                    throw new ArgumentNullException("requestEncoding");
                }
                HttpWebRequest request = null;
                //如果是发送HTTPS请求  
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    request = WebRequest.Create(url) as HttpWebRequest;
                    request.ProtocolVersion = HttpVersion.Version10;
                }
                else
                {
                    request = WebRequest.Create(url) as HttpWebRequest;
                }
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
    
                if (!string.IsNullOrEmpty(userAgent))
                {
                    request.UserAgent = userAgent;
                }
                else
                {
                    request.UserAgent = DefaultUserAgent;
                }
    
                if (timeout.HasValue)
                {
                    request.Timeout = timeout.Value;
                }
                if (cookies != null)
                {
                    request.CookieContainer = new CookieContainer();
                    request.CookieContainer.Add(cookies);
                }
                //如果需要POST数据  
                if (!(parameters == null || parameters.Count == 0))
                {
                    StringBuilder buffer = new StringBuilder();
                    int i = 0;
                    foreach (string key in parameters.Keys)
                    {
                        if (i > 0)
                        {
                            buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                        }
                        else
                        {
                            buffer.AppendFormat("{0}={1}", key, parameters[key]);
                        }
                        i++;
                    }
                    byte[] data = requestEncoding.GetBytes(buffer.ToString());
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }
                return request.GetResponse() as HttpWebResponse;
            }
    
            private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
            {
                return true; //总是接受  
            }
        }
    }
    View Code

    执行代码如下:

            public static void GetLinceNo()
            {
                using (TPMSEntities context = new TPMSEntities())
                {
                    List<dc_cb_SupplierLinceNo> lst = new List<dc_cb_SupplierLinceNo>();
                    var data = context.dc_p_Provider_temp2019.ToList();
                    foreach(var item in data)
                    {
                        if (!string.IsNullOrEmpty(item.LicenceNo))
                        {
                            continue;
                        }
                        string uri = string.Format("https://www.creditchina.gov.cn/api/public_search/getCreditCodeFacade?keyword={0}&_={1}", item.SupplierName, GetTimestamp(DateTime.Now));
                   
                        var json = HttpWebResponseUtility.GetUrl(uri);
                        if (!string.IsNullOrEmpty(json))
                        {
                            try
                            {
                                var jsonResult = JsonConvert.DeserializeObject<res>(json);
    
                                if (jsonResult != null && jsonResult.result != null && jsonResult.result.results != null)
                                {
                                    var model = jsonResult.result.results.Where(A => A.entName == item.SupplierName).FirstOrDefault();
                                    if (model == null)
                                    {
                                        continue;
                                    }
                                    string credCode = model.credCode;
                                    dc_cb_SupplierLinceNo d = new dc_cb_SupplierLinceNo();
                                    d.SupplierName = item.SupplierName;
                                    d.LinceNo = credCode;
                                    context.dc_cb_SupplierLinceNo.Add(d);
                                    context.SaveChanges();
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            catch(Exception ex)
                            {
                                continue;
                            }
                        }
                        else
                        {
                            continue;
                        }
    
                    }
                    //using (var Transaction = context.Database.BeginTransaction())
                    //{
                    //    try
                    //    {
                            
                    //        Transaction.Commit();
                    //    }
                    //    catch (Exception ex)
                    //    {
                    //        Transaction.Rollback();
                    //    }
                    //}
                }
            }
    
            public static string GetTimestamp(DateTime d)
            {
                TimeSpan ts = d - new DateTime(1970, 1, 1);
                return ts.TotalMilliseconds.ToString();
            }
            #endregion 
    
            public class res
            {
                public resultCls result { get; set; }
                public int totalPageCount { get; set; }
            }
    
            public class resultCls
            {
                public string start { get; set; }
                public string pageSize { get; set; }
                public string totalCount { get; set; }
                public List<resultsCls> results { get; set; }
                public string exportButtonValid { get; set; }
                public string currentPageNo { get; set; }
                public string page { get; set; }
                public string totalPageCount { get; set; }
              
            }
    
            public class resultsCls
            {
                public string id { get; set; }
                public string entName { get; set; }
                public string credCode { get; set; }
                public string regCode { get; set; }
                public string orgCode { get; set; }
                public string taxCode { get; set; }
    
                public string status { get; set; }
                public string modifyDate { get; set; }
                public string md5 { get; set; }
                public string rank { get; set; }
                public string solrStatus { get; set; }
                public string validTime { get; set; }
            }
    View Code

    虽说免费,但是这个方法服务端会限制请求的次数!

    @陈卧龙的博客

  • 相关阅读:
    POI中文API文档
    接口
    JDK中的URLConnection参数详解
    RPC远程过程调用概念及实现
    tkinter 打包成exe可执行文件
    PHP 的命令行模式
    php CLI SAPI 内置Web Server
    ppython的移位操作
    HAProxy基础
    HAProxy用法详解
  • 原文地址:https://www.cnblogs.com/chenwolong/p/linceno.html
Copyright © 2011-2022 走看看