WebResponse用法(根据省市区地址查询其邮编):
class Program { static string url { get; set; } static void Main(string[] args) { StringBuilder sb = new StringBuilder(); try { SqlConnection conn = new SqlConnection("自己的数据库连接语句"); SqlDataAdapter da = new SqlDataAdapter("查询语句", conn); DataSet ds = new DataSet(); Random rd = new Random(); da.Fill(ds); url = "http://opendata.baidu.com/post/s?wd={0}&rn=20";//请求地址 for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { var row = ds.Tables[0].Rows[i]; string keyworder = row["ProvinceName"] + " " + row["CityName"] + " " + row["DistrictName"]; sb.Append(GetZipCodeSql(keyworder, row["SysNo"].ToString())); Thread.Sleep(rd.Next(0, 1000));//延时 if (i != 0 && i % 100 == 0) { WriteTxt(sb.ToString()); sb.Clear(); } else if (i == ds.Tables[0].Rows.Count - 1) { WriteTxt(sb.ToString()); sb.Clear(); } } } catch (Exception ex) { System.Console.WriteLine(ex.Message); } } private static void WriteTxt(string text) { StreamWriter sw = File.AppendText("D:\3.txt");//保存输出的位置 sw.Write(text); sw.Close(); }
//得到邮编 private static string GetZipCodeSql(string keyworder, string sysNo) { StringBuilder sb = new StringBuilder(); try { HttpWebRequest httpweb = (HttpWebRequest)WebRequest.Create( new Uri(string.Format(url, HttpUtility.UrlEncode(keyworder, System.Text.Encoding.GetEncoding("GBK")))) ); WebResponse respon = httpweb.GetResponse(); StreamReader reader = new StreamReader(respon.GetResponseStream(), Encoding.GetEncoding("GBK")); string html = reader.ReadToEnd(); int statrtIndex = 0; int end = 0; string code = ""; statrtIndex = html.IndexOf("<ul><!-- baidu-tc begin -->"); if (statrtIndex > 0) { end = html.IndexOf("</a>", statrtIndex); statrtIndex = html.LastIndexOf("</em>", end); code = Regex.Replace(html.Substring(end - 22, 22), @"[^0-9]", ""); //code = html.Substring(end - 6, 6); sb.AppendFormat("UPDATE area SET ZipCode ={0} WHERE SysNo={1}; ", code, sysNo); } respon.Close(); } catch (Exception) { url = "http://opendata.baidu.com/post/s?wd={0}&p=mini&rn=20"; GetZipCodeSql(keyworder, sysNo); } return sb.ToString(); } }