版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shuimofengyang/article/details/84935128
package com.bigdata.std; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; public class BaiduAPIJW { private static String ak = "xxxxxxxxxxxxxxx";//自己申请的,密匙 public static Map<String, String> testPost(String x, String y) throws IOException { URL url = new URL("http://api.map.baidu.com/geocoder?" + ak + "=" + ak + "&callback=renderReverse&location=" + x + "," + y + "&output=json"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection .getOutputStream(), "utf-8"); out.flush(); out.close(); InputStream l_urlStream = connection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader( l_urlStream, "UTF-8")); StringBuilder sb = new StringBuilder(""); String res; while ((res = in.readLine()) != null) { //String res; sb.append(res.trim()); } String str = sb.toString(); System.out.println(str); Map<String, String> map = null; if (StringUtils.isNotEmpty(str)) { int addStart = str.indexOf("formatted_address\":"); int addEnd = str.indexOf("\",\"business"); if ((addStart > 0) && (addEnd > 0)) { String address = str.substring(addStart + 20, addEnd); map = new HashMap(); map.put("address", address); return map; } } return null; } public static void main(String[] args) throws IOException { Map<String, String> json = testPost("28.689577", "115.893524"); System.out.println("address :" + (String)json.get("address")); } }
结果:
{"status":"OK","result":{"location":{"lng":115.893524,"lat":28.689577},"formatted_address":"江西省南昌市东湖区叠山路535号","business":"豫章,滕王阁,大士院","addressComponent":{"city":"南昌市","direction":"附近","distance":"14","district":"东湖区","province":"江西省","street":"叠山路","street_number":"535号"},"cityCode":163}}
address :江西省南昌市东湖区叠山路535号