今天依據需求要從百度API中取出一些數據。這些操作包含:將坐標轉換成百度坐標。依據轉換的百度坐標進行特定的查詢。
有需求的收藏下,免得下次手寫浪費時間。
涉及到的操作有:JSON格式的字符解析。HTTP請求和獲得請求數據。文件流的寫入和讀出等等。
奉上源碼。共享:
首先是入口函數:
static void Main(string[] args) { Console.WriteLine("坐標轉換。信息查詢開始......"); string oFile = "C:\\Users\\MisterHu\\Desktop\\點加屬性\\聚類點.txt"; string iFile = "C:\\Users\\MisterHu\\Desktop\\點加屬性\\result.txt"; List<string> tCoords = new List<string>();//存轉換前坐標 List<string> cvtCoords = new List<string>();//存轉換后坐標 List<string> rstQuery = new List<string>();//存查詢結果 string sInfo; //暫時字符變量 StreamReader sr = new StreamReader(oFile, Encoding.Default); while ((sInfo = sr.ReadLine()) != null) { tCoords.Add(sInfo.Substring(sInfo.IndexOf(',')+1)); } sr.Close(); //轉換成百度坐標。然后存放到List中 BaiDuAPI.CoordConvert(tCoords, cvtCoords); //從List中取出每一個坐標。然后調用API BaiDuAPI.PlaceAPI(cvtCoords, rstQuery); //寫入文件。 String strLine = null; for (int i = 1; i <= 1000;++i ) { strLine += i.ToString() + "," + tCoords[i - 1] + rstQuery[i - 1] + "\r\n"; } FileStream.WriteInFile(strLine, iFile); Console.WriteLine("轉換,獲取,完畢!"); }
字符串輸入輸出到文件:
//輸入輸出字符到文件里 public static class FileStream { public static void ReadFormFile(string path) { } public static void WriteInFile(string content,string path) { string iFile = "D:\\temp.txt"; if (path == null) path = iFile; StreamWriter sw = new StreamWriter(path); sw.Write(content); sw.Flush(); sw.Close(); } }核心類,細致看,依據自己的需求能夠做適當的改動:
//處理API請求 public static class BaiDuAPI { public static void CoordConvert(List<string> src,List<string> des) { StringBuilder RequestURL = new StringBuilder(); StringBuilder coordStr = new StringBuilder(); string arg1 = "http://api.map.baidu.com/geoconv/v1/?coords="; string arg2 = "&from=1&to=5&ak=IC96AbO521APtmpsaR9xCMqo"; string result = null; int count = src.Count; for (int i = 0; i < count; ++i) { if ((i+1)%100 != 0 && i != count - 1) //將100個數據加進去 { coordStr.Append(src[i]); coordStr.Append(";"); continue; } else if ((i + 1) % 100 == 0 || i == count - 1) //處理不足100個數據和第100個數據 { coordStr.Append(src[i]); } RequestURL.Append(arg1); RequestURL.Append(coordStr); RequestURL.Append(arg2); result = HttpGet(RequestURL.ToString()); //處理返回的結果 DoJsonCoords(result,des); result = null; RequestURL.Clear(); coordStr.Clear(); } } public static void DoJsonCoords(string result, List<string> des) { if (result == "" || result == null) return; JsonCoord jsonCoord = JSON.ParseJson<JsonCoord>(result); List<Coord> coord = jsonCoord.result; string temp = null; foreach (Coord crd in coord) { temp = crd.y.ToString() + "," + crd.x.ToString(); des.Add(temp); } } /// <summary> /// 返回結果字符串 /// </summary> public static void PlaceAPI(List<string> des,List<string> rst) { //購物//教育//景點//企業//小區 List<string> query = new List<string>{ "購物", "教育","景點","企業", "小區"}; StringBuilder RequestURL = new StringBuilder(); StringBuilder tempQuery = new StringBuilder(); string arg1 = "http://api.map.baidu.com/place/v2/search?
ak=IC96AbO521APtmpsaR9xCMqo&output=json&query="; string arg2 = "&page_size=1&page_num=0&scope=1&location="; string arg3 = "&radius=1000"; string jsonResult = null; string tStr = null; int num; foreach (string str in des) { for (int i = 0; i < 5;++i ) { tempQuery.Append(HttpUtility.UrlEncode(query[i])); tempQuery.Append(arg2); tempQuery.Append(str); tempQuery.Append(arg3); RequestURL.Append(arg1); RequestURL.Append(tempQuery.ToString()); jsonResult = HttpGet(RequestURL.ToString()); num = DoJsonPlace(jsonResult); tStr += "," + query[i] + num.ToString(); tempQuery.Clear(); RequestURL.Clear(); } rst.Add(tStr); Console.WriteLine(tStr); tStr = null; } } public static int DoJsonPlace(string result) { if (result == "" || result == null) return -1; Place place = JSON.ParseJson<Place>(result); return place.total; } /// <summary> /// 通過url獲取返回來的字符串 /// </summary> private static string HttpGet(string requestURL) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL.ToString()); request.Method = "GET"; request.ServicePoint.Expect100Continue = false; request.Method = "GET"; request.KeepAlive = true; request.UserAgent = ".NET Framework BsiDuAPI Client"; request.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; HttpWebResponse response = null; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException webEx) { if (webEx.Status == WebExceptionStatus.Timeout) { response = null; } Console.WriteLine(webEx.Status.ToString()); } if (response != null) { if (response.CharacterSet != null) { Encoding encoding = Encoding.GetEncoding(response.CharacterSet); return GetResponseAsString(response, encoding); } else { return string.Empty; } } else { return string.Empty; } } private static string GetResponseAsString(HttpWebResponse response, Encoding encoding) { StringBuilder result = new StringBuilder(); Stream stream = null; StreamReader reader = null; try { // 以字符流的方式讀取HTTP響應 stream = response.GetResponseStream(); reader = new StreamReader(stream, encoding); // 每次讀取不大於256個字符,並寫入字符串 char[] buffer = new char[256]; int readBytes = 0; while ((readBytes = reader.Read(buffer, 0, buffer.Length)) > 0) { result.Append(buffer, 0, readBytes); } } catch (WebException webEx) { if (webEx.Status == WebExceptionStatus.Timeout) { result = new StringBuilder(); } } finally { // 釋放資源 if (reader != null) reader.Close(); if (stream != null) stream.Close(); if (response != null) response.Close(); } return result.ToString(); } }
解析Json的類,沒什么好說的直接copy:
//Json解析 public static class JSON { /// <summary> /// 將Json反序列化為T對象 /// </summary> public static T ParseJson<T>(string jsonString) { using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString))) { return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(ms); } } /// <summary> /// 將對象序列化為Json /// </summary> public static string Stringify(object jsonObject) { using (var ms = new MemoryStream()) { new DataContractJsonSerializer(jsonObject.GetType()).WriteObject(ms, jsonObject); return Encoding.UTF8.GetString(ms.ToArray()); } } } //序列化對象 [DataContract] public class Coord { [DataMember] public float x {get;set;} [DataMember] public float y {get;set;} } [DataContract] public class JsonCoord { [DataMember] public int status { get; set; } [DataMember] public List<Coord> result { get; set; } } [DataContract] public class Place { [DataMember] public int status { get; set; } [DataMember] public string message { get; set; } [DataMember] public int total { get; set; } //結果沒用,不獲取。 //[DataMember(IsRequired = false)] //public string results { get; set; } }
注意。序列化對象類的寫法,值得提出的一點是當不須要某個節點時。能夠不用寫出來,就像results一樣。由於我的需求根本不關心當中的內容。
最后,附上源碼文件:http://download.csdn.net/detail/z702143700/8777263