通过ip定位经纬度,城市与国家

3,286 阅读1分钟

因为公司最近要做一个ip查询经纬度在地图上显示的功能,而且有海外的ip,所以高德地图百度地图这些收费的api就暂时先不考虑了。

寻觅了良久,终于找了一个符合我们目前需求的在线api,官网地址:ip-api.com/docs/api:js…,还支持各种语言的返回结果哦

在这里插入图片描述 在这里插入图片描述

现在来写例子吧

pom.xml 加入httpclient,fastjson,lombok依赖


        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.12</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.72</version>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * 通过ip定位地址,经纬度,城市,国家等
 * api地址:https://ip-api.com/docs/api:json
 *
 * @author miao
 */
@Slf4j
public class IpUtil {

    /**
     * 发起https请求并获取结果
     *
     * @param requestUrl 请求地址
     * @return JSONObject(通过JSONObject.get ( key)的方式获取json对象的属性值)
     */
    public static JSONObject doGetRequest(String requestUrl) {
        //1.获得一个httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //2.生成一个get请求
        HttpGet httpget = new HttpGet(requestUrl);
        CloseableHttpResponse response = null;
        try {
            //3.执行get请求并返回结果
            response = httpclient.execute(httpget);
        } catch (IOException e1) {

            log.info("请求:{}时出错", requestUrl);
        }
        String result = null;
        try {
            //4.处理结果,这里将结果返回为字符串

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            }
        } catch (ParseException | IOException e) {

            log.info("处理请求结果出错");
        } finally {
            try {

                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return JSON.parseObject(result);
    }
    
    public static void main(String[] args) {
        String requestUrl = "http://ip-api.com/json/103.29.66.52?lang=zh-CN";
        System.out.println(IpUtil.doGetRequest(requestUrl));
    }
}

输出结果:经纬度与国家城市都有了

在这里插入图片描述