天地图API调用注意事项

天地图API调用注意事项

浏览器端

服务器端调用时

使用干净的 HTTPRequest

一些封装好的HTTPClient 可能会自动引入一些 UserAgent Header,导致请求被 识别为 非服务器请求。

参数拼接

参数结构有点出人意料。

使用 URIBuilder 辅助拼接,不然可能会导致 URI 异常。

示例代码:

java 复制代码
@AllArgsConstructor
public class TianMapService implements MapService {

    private final String SERVER;

    private final String KEY;

    @Data
    private class TianMapLocation {
        private String level;
        private String lon;
        private String lat;
        private String keyWord;
        private int score;
    }

    @Data
    private class TianMapResp {
        private int code;
        private int status;
        private String msg;
        private String resolve;
        private TianMapLocation location;
        private String searchVersion;
    }

    @Override
    public String getCoordType() {
        return "GCJ-02";
    }

    @Override
    public GetLocationResult getLocationInfo(String address) {
        String server = this.SERVER + "/geocoder";

        Map<String, String> params = new HashMap<>(2);
        Map<String, String> keywords = new HashMap<>(1);
        keywords.put("keyWord", address);
        params.put("ds", JSON.toJSONString(keywords));
        params.put("tk", this.KEY);

        String res = SimpleHTTP.getContent(server, params);
        TianMapResp tianMapResp = JSON.parseObject(res, TianMapResp.class);
        if (0 != tianMapResp.getStatus() || 0 != tianMapResp.getCode()) {
            if (null != tianMapResp.getResolve()) {
                return GetLocationResult.fail(tianMapResp.getResolve(), res);
            }
            return GetLocationResult.fail(tianMapResp.getMsg(), res);
        }
        return GetLocationResult.success(Location.of(tianMapResp.getLocation().getLat(), tianMapResp.getLocation().getLon(), getCoordType()), res);
    }

    public static void main(String[] args) {
        TianMapService service = new TianMapService("https://api.tianditu.gov.cn", "xxx");
        System.out.println(service.getLocationInfo("北京市海淀区莲花池西路28号"));
    }
}
java 复制代码
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.HeaderGroup;
import org.apache.hc.core5.net.URIBuilder;

import java.net.URI;
import java.util.Map;

public class SimpleHTTP {

    public static String getContent(String url, Map<String, String> args) {
        URIBuilder uriBuilder = null;
        String finalUrl = null;
        try {
            uriBuilder = new URIBuilder(url);
            for (Map.Entry<String, String> entry : args.entrySet()) {
                uriBuilder.addParameter(entry.getKey(), entry.getValue());
            }
            URI finalUri = uriBuilder.build();
            finalUrl = finalUri.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 3. 创建GET请求
            HttpGet request = new HttpGet(finalUrl);
            // 4. 【关键步骤】设置"纯净"的请求头,覆盖或清除浏览器特征
            // 移除所有默认头,然后只添加最必要的
            request.setHeaders(new HeaderGroup().getHeaders()); // 先清空
            // 只添加最核心、最中性的请求头
            request.setHeader("User-Agent", "Java-ServerClient/1.0"); // 自定义服务器UA
            // 5. 发送请求并处理响应
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String result = EntityUtils.toString(entity);
                    return result;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "";
    }
}
相关推荐
来杯@Java3 小时前
图书管理系统(基于springboot+vue前后端分离的项目)计算机毕业设计java
java·spring boot·spring·vue·毕业设计·mybatis·课程设计
卷毛的技术笔记4 小时前
告别硬编码!Spring AI Alibaba 实现 AI Agent 智能工具调用(Tool Calling)
java·人工智能·后端·python·spring·ai编程
编程大师哥4 小时前
匿名函数 lambda + 高阶函数
java·python·算法
東雪木4 小时前
多线程与并发编程 专属复习笔记
java·开发语言·笔记·java面试
adrninistrat0r4 小时前
Java调用链MCP分析工具
java·python·ai编程
噜噜噜阿鲁~4 小时前
python学习笔记 | 11.3、面向对象高级编程-多重继承
java·开发语言
春生野草5 小时前
反射、Tomcat执行
java·开发语言
_日拱一卒6 小时前
LeetCode:207课程表
java·数据结构·算法·leetcode·职场和发展
飞翔中文网6 小时前
Java学习笔记之抽象类与接口(设计思想)
java·笔记·学习
qcx236 小时前
【系统学AI】09 Multi-Agent架构(2026版):从学术理论到工业级实践
java·人工智能·架构·multi-agent·claude agent