天地图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 "";
    }
}
相关推荐
小bo波13 小时前
从"任意文件复制"深挖Java I/O:字符流与字节流的本质抉择
java·nio·io流·后端开发·文件复制
nanxun8862 天前
记一次诡异的 Docker 容器"串包"故障排查
java
用户1563068103512 天前
Day01 | Java 基础(Java SE)
java
行者全栈架构师2 天前
Maven dependency:tree 的 8 个高级用法
java·后端
行者全栈架构师2 天前
IDEA 中 Maven 项目的 15 个红色报错快速解决方法
java·后端
令人头秃的代码0_02 天前
mac(m5)平台编译openjdk
java
唐青枫3 天前
Java JDBC 实战指南:从 Connection 到事务和连接池
java
一个做软件开发的牛马3 天前
MyBatis-Plus 从零实战:完整搭建可运行 Demo,BaseMapper 零 SQL、Wrapper 条件构造、分页插件与代码生成器详解
java·后端
用户3721574261353 天前
Java 处理 PDF 图片:提取 PDF 中的图片,并压缩 PDF 图片体积
java
用户3721574261353 天前
Java 打印 Word 文档:从基础打印到高级设置
java