天地图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 "";
    }
}
相关推荐
芒果披萨2 小时前
sql存储过程
java·开发语言·数据库
yaoxin5211232 小时前
368. Java IO API - 基本文件属性
java·开发语言·python
_日拱一卒2 小时前
LeetCode:最小覆盖字串
java·数据结构·算法·leetcode·职场和发展
禾小西2 小时前
性能测试后的瓶颈定位与调优:自下而上找问题,自上而下解难题
java·测试工具
建军啊2 小时前
java审计进阶
java·开发语言·python
2401_889626922 小时前
Java流程控制与方法全解析
java·开发语言
花千树-0102 小时前
5分钟用 Java 构建你的第一个 AI 应用
java·人工智能·spring boot·langchain·aigc·ai编程
pedestrian_h2 小时前
Java单例模式回顾
java·单例模式·设计模式
a8a3022 小时前
Spring Boot(快速上手)
java·spring boot·后端