百度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] + "\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
百度API调用实例的更多相关文章
- 腾讯QQAndroid API调用实例(QQ分享无需登录)
腾讯QQAndroid API调用实例(QQ分享无需登录) 主要分为两个步骤: 配置Androidmanifest.xml 修改activity里边代码 具体修改如下: 1.Activity代 ...
- 百度地图API调用实例之地址标注与位置显示
之前弄了个谷歌地图API标注的调用实例,后来要求改成百度地图. 感谢主,通过网上资料(百度地图API,百度地图API详解之地图标注)收集及研究, 终于把百度地图标注和显示功能实现出来了,具体实现方法如 ...
- Python爬虫之百度API调用
调用百度API获取经纬度信息. import requests import json address = input('请输入地点:') par = {'address': address, 'ke ...
- 毕设(一)C#的百度api调用
这个学期就要毕业了,选了一个无人机地面站软件设计的题目,这几天也开始着手做, 首先做了一个百度地图的调用,这里因为是上位机的开发,所有就不介绍Javascript的 调用方法,核心是用到一个类Http ...
- H5Plus 入门学习-Dcloud H5+ API调用实例
使用API Reference完整简单的操作,更多操作查看官方文档. 最后提供项目的下载地址[下载][一款移动APP演示]
- PHP+百度地图API+JAVASCRIPT实现GPS坐标与百度坐标转换的实例
原文:PHP+百度地图API+JAVASCRIPT实现GPS坐标与百度坐标转换的实例 <!--小幅的坐标转换点位程序--> <!DOCTYPE html> <html&g ...
- 调用百度API进行文本纠错
毕设做的是文本纠错方面,然后今天进组见研究生导师 .老师对我做的东西蛮感兴趣.然后介绍自己现在做的一些项目,其中有个模块需要有用到文本纠错功能. 要求1:有多人同时在线编辑文档,然后文档功能有类似Wo ...
- Vue 通过调用百度API获取地理位置-经度纬度省份城市
一.首先在百度api注册获得ak密钥 二.新建js文件,我命名为loadBMap.js,里面创建script,代码如下: /** * 加载地图 * @param {Function} callback ...
- WPF技术触屏上的应用系列(二): 嵌入百度地图、API调用及结合本地数据库在地图上进行自定义标点的实现
原文:WPF技术触屏上的应用系列(二): 嵌入百度地图.API调用及结合本地数据库在地图上进行自定义标点的实现 去年某客户单位要做个大屏触屏应用,要对档案资源进行展示之用.客户端是Window7操作系 ...
随机推荐
- JS 前端 将图片转换为Base64利用H5 FileReader新特性
file = document.getElementById("image"); var file=file.files[0]; var fileName=file.name; ...
- 洛谷P3254 圆桌问题 网络流_二分图
Code: #include<cstdio> #include<algorithm> #include<vector> #include<queue> ...
- 【模板】多项式乘法 NTT
相对来说是封装好的,可以当模板来用. #include <bits/stdc++.h> #define maxn 5000000 #define G 3 #define ll long l ...
- linux查看系统cpu信息
# 查看物理CPU个数 cat /proc/cpuinfo| grep "physical id"| sort| uniq| wc -l # 查看每个物理CPU中core的个数(即 ...
- spring boot ---web应用开发-错误处理
一.错误的处理 方法一:Spring Boot 将所有的错误默认映射到/error, 实现ErrorController @Controller @RequestMapping(value = &qu ...
- PHP 变量作用域
以下为 PHP 中的各种变量在底层实现中是如何存储的. 变量: $temp = 'temp'; $temp2 = $temp; // key p *executor_globals.symbol_ta ...
- [HAOI2015]树上染色(树形dp)
[HAOI2015]树上染色 题目描述 有一棵点数为 N 的树,树边有边权.给你一个在 0~ N 之内的正整数 K ,你要在这棵树中选择 K个点,将其染成黑色,并将其他 的N-K个点染成白色 . 将所 ...
- 【Henu ACM Round#24 D】Iterated Linear Function
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 把B提取出来就是一个等比数列了. 求和一下会发现是这种形式. \(B*\frac{(A^n-1)}{A-1}+A^n*x\) 则求一 ...
- 精品JS代码收藏大全
1. oncontextmenu="window.event.returnvalue=false" 将彻底屏蔽鼠标右键 <table border oncontextmenu ...
- @SpringBootApplication cannot be resolved to a type In STS
@SpringBootApplication cannot be resolved to a type In STS 学习了:https://stackoverflow.com/questions/4 ...