BaiduMapApi 实现ip城市获取

第一步申请百度map AK

第二步 查看 百度api服务文档

第三步 编写 api工具类


import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
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;

/**
 * title:
 *
 * @author atcode
 * @createDate 2023/3/11   16:02
 */
@Component
public class MyBaiduMapApi {

    public static String getCityByIP(String ip) throws IOException, JSONException {
        String address = "";
        String ak = "3IXm4vC9V69cP6ce5l1KodvuPEiaV5VQ";
        // https://lbsyun.baidu.com/index.php?title=webapi/ip-api
        String apiUrl="http://api.map.baidu.com/location/ip";
        String url=apiUrl+"?ip=" + ip + "&ak=" + ak+"&coor=bd09ll";
        InputStream is = new URL(url).openStream();
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            int cp;
            while ((cp = rd.read()) != -1) {
                sb.append((char) cp);
            }
            String jsonText = sb.toString();
            JSONObject resultJson = JSONObject.parseObject(jsonText);

            address = ((JSONObject) resultJson.get("content")).getString("address");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            is.close();
        }
        return address;
    }

}

第四步 编写 Controller 类


import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping; 
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException; 

/**
 * title:
 *
 * @author atcode
 * @createDate 2023/3/11   16:15
 */
@Controller
public class MyIndex {
    @Autowired
    private MyBaiduMapApi myBaiduMapApi;

    @GetMapping("/")
    public String getIpAddress(HttpServletRequest request) {

        String ipAddress = this.getIp(request);

        request.setAttribute("mycity", "您所在的城市是"+BaiduMapUtil.getAddress(ipAddress));

        return "index.html";
    }

    /**
     * 获取IP地址
     * @param request
     * @return
     */
    private String getIp( HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress="";
        }
        // ipAddress = this.getRequest().getRemoteAddr();

        return ipAddress;
    }
}

第五步 编写 页面 html

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
baidu API 测试<br/>
 <p th:text="${mycity}">Original Value</p>
</body>
</html>

注意实现 pom.xml 需要引入 thymeleaf依赖

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.5.14</version>
        </dependency>

项目演示:atcode.club

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值