天地图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 "";
    }
}
相关推荐
CodeStride16 小时前
就像长跑配速一样,我是如何平衡代码性能与可读性的
java
弹简特16 小时前
【Java项目-企悦抽】07-用户与认证模块-实现用户注册01
java·开发语言
山东点狮信息科技有限公司16 小时前
SpringBoot+VUE3,一套系统完成OA+HRM+CRM+MES+合同+项目管理 —— 深度解析点狮全业务管理平台
java·spring boot·后端
snow@li17 小时前
Java:Java 服务器(Web 容器 / Servlet 容器)完整工作清单
java·服务器·前端
青山木17 小时前
Hot 100 --- 二叉树与递归
java·数据结构·算法·leetcode·深度优先
jason成都18 小时前
GNSS-QC 数据清洗功能全面增强|滑坡监测实测验证,适配 rtklib_java 高精度解算链路
java·gnss
前端工作日常18 小时前
我学习到的Java概念
java·后端
卓怡学长18 小时前
w263基于springboot + vue 健康饮食管理系统
java·数据库·vue.js·spring boot·spring·intellij-idea
r_oo_ki_e_18 小时前
Java反射机制学习笔记
java·笔记·学习
九皇叔叔18 小时前
RHEL9.8 配置本地镜像仓库
android·java·缓存