使用C#獲取統計局行政區划代碼


在統計局官網提供了每年最新的PAC代碼,方便大家查詢,但沒有提供完整版的下載,於是"手工"把它復制下來了。

http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/

此工具有兩個關鍵點:

1、Get函數中要注意編碼問題,要去讀取它是什么編碼方式,否則可能是亂碼;由於網速或服務器等原因,每一次請求時可以休眠100毫秒,每當出現404或服務器中斷等情況時,線程暫停2秒再試(目前第二次Get都正常);

2、第二個關鍵點是年份、省、市、縣、鄉、村的解析,當然是正則表達式來處理。

下面是HTTP請求代碼示例:

public static string RequestGet(string strUrl, string level="")
{
    strUrl = strUrl.Replace(" ", "");
    string outString="";
    try
    {
        HttpWebResponse httpWebResponse = null;
        if (!Regex.IsMatch(strUrl, @"^https?://", RegexOptions.IgnoreCase))
            strUrl = "http://" + strUrl;
        if (WebRequest.Create(strUrl) is HttpWebRequest httpWebRequest)
        {
            httpWebRequest.Timeout = timeOut;
            httpWebRequest.ReadWriteTimeout = 60000;
            httpWebRequest.AllowAutoRedirect = true;
            httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; Maxthon 2.0)";
            httpWebResponse = (HttpWebResponse) httpWebRequest.GetResponse();
        }

        if (httpWebResponse != null && httpWebResponse.ContentType.ToLower().IndexOf("text/html", StringComparison.Ordinal) == -1)
        {
            httpWebResponse.Close();
            return string.Empty;
        }
        using (Stream stream = httpWebResponse.GetResponseStream())
        {
            List<byte> lst = new List<byte>();
            int nRead = 0;
            while ((nRead = stream.ReadByte()) != -1) lst.Add((byte)nRead);
            byte[] byHtml = lst.ToArray();
            outString = Encoding.UTF8.GetString(byHtml, 0, byHtml.Length);
            string strCharSet = Regex.Match(outString, @"<meta.*?charset=""?([a-z0-9-]+)\b", RegexOptions.IgnoreCase).Groups[1].Value;
            if (strCharSet != "" && (strCharSet.ToLower().IndexOf("utf") == -1))
            {
                outString = Encoding.GetEncoding(strCharSet).GetString(byHtml, 0, byHtml.Length);
            }
        }

        return outString;
    }
    catch (Exception exception1)
    {
        Console.WriteLine(@"-------------------------------");
        ErrorUrl.Add(strUrl);
        Console.WriteLine($@"首次獲取失敗:{ exception1.Message},{strUrl}");
        //暫停2秒
        Thread.Sleep(2000);
        try
        {
            outString= RequestGet(strUrl, level);
            ErrorUrl.Remove(strUrl);
            Console.WriteLine(@"暫停2秒后成功。");
        }
        catch (Exception exception2)
        {
            //暫停5秒
            Thread.Sleep(5000);
            Console.WriteLine($@"再次獲取失敗:{ exception2.Message},{strUrl}");
            try
            {
                outString= RequestGet(strUrl, level);
                ErrorUrl.Remove(strUrl);
                Console.WriteLine(@"暫停5秒后成功。");
            }
            catch (Exception exception3)
            {
                Console.WriteLine($@"放棄獲取:{ exception3.Message},{strUrl}");
                outString = "";
            }
        }
        return outString;
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM