MCPcopy Create free account
hub / github.com/LisenCoding/cangku / BaiduUtil

Class BaiduUtil

boot/src/main/java/com/utils/BaiduUtil.java:20–98  ·  view source on GitHub ↗

@author yangliyuan @version 创建时间:2024年3月28日 下午9:37:05 类说明 :

Source from the content-addressed store, hash-verified

18*/
19
20public class BaiduUtil {
21
22 /**
23 * 根据经纬度获得省市区信息
24 * @param lon 纬度
25 * @param lat 经度
26 * @param coordtype 经纬度坐标系
27 * @return
28 */
29 public static Map<String, String> getCityByLonLat(String key, String lng, String lat) {
30 String location = lat + "," + lng;
31 try {
32 //拼装url
33 String url = "http://api.map.baidu.com/reverse_geocoding/v3/?ak="+key+"&output=json&coordtype=wgs84ll&location="+location;
34 String result = HttpClientUtils.doGet(url);
35 JSONObject o = new JSONObject(result);
36 Map<String, String> area = new HashMap<>();
37 area.put("province", o.getJSONObject("result").getJSONObject("addressComponent").getString("province"));
38 area.put("city", o.getJSONObject("result").getJSONObject("addressComponent").getString("city"));
39 area.put("district", o.getJSONObject("result").getJSONObject("addressComponent").getString("district"));
40 area.put("street", o.getJSONObject("result").getJSONObject("addressComponent").getString("street"));
41 return area;
42 }catch (Exception e) {
43 e.printStackTrace();
44 }
45 return null;
46 }
47
48 /**
49 * 获取API访问token
50 * 该token有一定的有效期,需要自行管理,当失效时需重新获取.
51 * @param ak - 百度云官网获取的 API Key
52 * @param sk - 百度云官网获取的 Securet Key
53 * @return assess_token
54 */
55 public static String getAuth(String ak, String sk) {
56 // 获取token地址
57 String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
58 String getAccessTokenUrl = authHost
59 // 1. grant_type为固定参数
60 + "grant_type=client_credentials"
61 // 2. 官网获取的 API Key
62 + "&client_id=" + ak
63 // 3. 官网获取的 Secret Key
64 + "&client_secret=" + sk;
65 try {
66 URL realUrl = new URL(getAccessTokenUrl);
67 // 打开和URL之间的连接
68 HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
69 connection.setRequestMethod("GET");
70 connection.connect();
71 // 获取所有响应头字段
72 Map<String, List<String>> map = connection.getHeaderFields();
73 // 遍历所有的响应头字段
74 for (String key : map.keySet()) {
75 System.err.println(key + "--->" + map.get(key));
76 }
77 // 定义 BufferedReader输入流来读取URL的响应

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected