天天看點

springboot 整合百度地圖 API前言正文

前言

正文

1. 建立百度賬号,申請成為開發者 :

springboot 整合百度地圖 API前言正文

 2. 建立應用,得到ak :

springboot 整合百度地圖 API前言正文

3. ok,可以開始使用了 ,具體API文檔可以看官方 :https://lbsyun.baidu.com/index.php?title=webapi/ip-api

springboot 整合百度地圖 API前言正文

封裝好的對接執行個體, 我們就拿 普通IP定位作為示例:

BaiduAddressUtil.java

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;

/**
 * @Author JCccc
 * @Description
 * @Date 2021/7/14 9:34
 */
@Component
public class BaiduAddressUtil {

    /**
     * 百度地圖申請的ak
     */
    @Value("${baidu.map.ak}")
    private String AK;

    public String getAddress(String ip) {
        String address = "";
        try {
            // 這裡調用百度的ip定位api服務 詳見 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
            JSONObject resultJson = readJsonFromUrl("http://api.map.baidu.com/location/ip?ip=" + ip + "&ak=" + AK);
            //resultJson 是傳回結果,目前隻取位置資訊
            address = ((JSONObject) resultJson.get("content")).getString("address");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return address;
    }

    /**
     * 讀取
     *
     * @param rd
     * @return
     * @throws IOException
     */
    private static String readAll(BufferedReader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }

    /**
     * 建立連結
     *
     * @param url
     * @return
     * @throws IOException
     * @throws JSONException
     */
    private static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        InputStream is = new URL(url).openStream();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = JSONObject.parseObject(jsonText);
            return json;
        } finally {
            is.close();
        }
    }
}
           

結果示例:

springboot 整合百度地圖 API前言正文

好,就到這。