java調用百度地圖API反解析經緯碼返回地址信息

import java.net.URL;
import java.util.Map;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import org.apache.commons.lang.StringUtils;

public class BaiduAPI {
	private static String ak = "5ef2641d89438a6e708db122820cf1d2";
    
    public static Map<String, String> testPost(String x, String y) throws IOException {
        URL url = new URL("http://api.map.baidu.com/geocoder?" + ak + "=您的密鑰" + 
        		"&callback=renderReverse&location=" + x
                        + "," + y + "&output=json");
        URLConnection connection = url.openConnection();
        /**
         * 然後把連接設爲輸出模式。URLConnection通常作爲輸入來使用,比如下載一個Web頁。
         * 通過把URLConnection設爲輸出,你可以把數據向你個Web頁傳送。下面是如何做:
         */
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(connection
                .getOutputStream(), "utf-8");
//        remember to clean up
        out.flush();
        out.close();
//        一旦發送成功,用以下方法就可以得到服務器的迴應:
        String res;
        InputStream l_urlStream;
        l_urlStream = connection.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                l_urlStream,"UTF-8"));
        StringBuilder sb = new StringBuilder("");
        while ((res = in.readLine()) != null) {
            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<String,String>();
				map.put("address", address);
				return map;		
			}
		}
		
		return null;
		
    }
	
	public static void main(String[] args) throws IOException {
    	Map<String, String> json = BaiduAPI.testPost("29.542938", "114.064022");
        System.out.println("address :" + json.get("address"));
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章