天地图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 "";
    }
}
相关推荐
TE-茶叶蛋19 小时前
深入研究 yudao-framework 模块:Java 编程能力提升指南
java·开发语言
逻辑驱动的ken19 小时前
Java高频考点场景题24
java·开发语言·面试·职场和发展·求职招聘
兔小盈19 小时前
多线程-(五)线程安全之内存可见性
java·开发语言·多线程
CeshirenTester19 小时前
LangChain的工具调用 vs 原生Skill API:性能差在哪儿?
java·人工智能·langchain
yaoxin52112320 小时前
400. Java 文件操作基础 - 使用 Buffered Stream I/O 读取文本文件
java·开发语言·python
Fox爱分享20 小时前
字节二面:10亿数据毫秒级查手机尾号后4位,答不出“异构索引”直接挂?
java·后端·面试
61900833620 小时前
win idea 控制台中文乱码
java·ide·intellij-idea
折哥的程序人生 · 物流技术专研20 小时前
《Java面试85题图解版(二)》进阶深化上篇:并发编程 + JVM
java·开发语言·后端·面试
abcnull20 小时前
用ASM做精准测试(Java)
java·jar·asm·字节码·精准测试
@杰克成20 小时前
Java学习26
java·学习·idea