百度API调用实例

今天依据需求要从百度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] + "
";           
            }

            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






原文地址:https://www.cnblogs.com/cynchanpin/p/7028181.html