SpringBoot 接入腾讯地图

本文介绍了如何在SpringBoot项目中集成腾讯地图API,包括注册应用、添加密钥、获取地址列表和按关键词搜索地址的过程,以及如何处理API响应数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一步 注册腾讯地图api

1. 到腾讯地图api注册一下

https://lbs.qq.com/dev/console/application/mine

2. 创建你自己的应用

在这里插入图片描述
在这里插入图片描述
添加一下key
在这里插入图片描述
添加之后就有key了
在这里插入图片描述
添加之后还需要分配额度才能使用,到账户额度去给这个key配额
在这里插入图片描述
这样分配额度
在这里插入图片描述
然后到应用里面详情就能看到刚刚分配的额度了
在这里插入图片描述
这样就能调用接口请求了
在这里插入图片描述
腾讯地图接口文档:https://lbs.qq.com/service/webService/webServiceGuide/search/webServiceDistrict

第二步:集成SpringBoot

1. 需要用到的依赖

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.9.1</version>
</dependency>

2. 代码片段

public class TencentMapUtils {
    private static final String KEY = "2A6BZ-MBOKU-CP3VE-GUS4B-25UHZ-6CF5U";
 	// 省市区列表url
    private static final String LIST_URL = "https://apis.map.qq.com/ws/district/v1/list";
    //关键词获取行政区域
    private static final String KEYWORD_URL = "https://apis.map.qq.com/ws/district/v1/search";
    
    /**
     * 获取地址列表
     *
     * @return 省市区地址
     */
    private static List<List<Address>> getList() {
        Gson gson = new Gson();
        String addressData = fetchDataFromAPI(LIST_URL + "?key=" + KEY);
        JsonObject jsonObject = new Gson().fromJson(addressData, JsonObject.class);
        JsonArray jsonArray = jsonObject.getAsJsonArray("result");
        for (JsonElement jsonElement : jsonArray) {
            List<Address> addressList = gson.fromJson(jsonElement, new TypeToken<List<Address>>() {
            }.getType());
            list.add(addressList);
        }
        return list;
    }
    
    public static List<Address> searchByKeyword(String keyword) {
//        https://apis.map.qq.com/ws/district/v1/search?&keyword=香格里拉&key=[你的key]
        String addressData = fetchDataFromAPI(KEYWORD_URL + "?keyword=" + keyword + "&key=" + KEY);
        return mapDataHandler(addressData);
    }

	/**
     * 地图json字符串转list
     *
     * @param addressData
     * @return
     */
    private static List<Address> mapDataHandler(String addressData) {
        if (StringUtils.isBlank(addressData)) {
            return null;
        }
        List<Address> addressList = null;
        JsonObject jsonObject = new Gson().fromJson(addressData, JsonObject.class);
        JsonArray jsonArray = jsonObject.getAsJsonArray("result");
        if (jsonArray != null && !jsonArray.isJsonNull()) {
            addressList = gson.fromJson(jsonArray.get(0), new TypeToken<List<Address>>() {
            }.getType());
        } else {
            return null;
        }
        return addressList;
    }

	private static String fetchDataFromAPI(String apiUrl) {
        StringBuilder response = new StringBuilder();
        try {
            URL url = new URL(apiUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-Type", "application/json");

            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response.toString();
    }
 }

根据自己的接收数据创建实体类

@Data
public class Address {


    private Integer id;
    private String name;
    private String fullname;
    private String[] pinyin;
    private Location location;
    private Integer[] cidx;
    private List<Address> childs;
    @Data
    public class Location {
        private String lat;
        private String lng;
    }
}
### Spring Boot 整合 Spring Security 实现认证与授权 #### 项目准备 为了使Spring Boot应用能够快速集成Spring Security,仅需引入相应的Starter依赖。这使得开发者可以专注于业务逻辑开发而非安全机制的构建[^1]。 对于Maven项目,在`pom.xml`文件中加入如下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` #### 配置类编写 创建一个继承自`WebSecurityConfigurerAdapter`的安全配置类来定义具体的保护策略。该适配器允许覆盖方法来自定义身份验证管理器、HTTP请求过滤链以及其他重要的设置项[^2]。 ```java @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() // 如果不需要CSRF保护则关闭它 .authorizeRequests() .antMatchers("/login", "/register").permitAll() // 对登录注册页面放行 .anyRequest().authenticated(); // 所有其他请求都需要经过身份验证 http.formLogin(); } } ``` 上述代码片段展示了如何通过重写`configure()`函数指定哪些URL路径应该公开访问以及哪些需要用户先完成登录才能查看。同时启用了表单登陆方式作为默认的身份验证入口。 #### 用户详情服务实现 为了让应用程序知道谁是合法用户及其权限级别,通常会实现`UserDetailsService`接口并覆写其中的方法返回特定用户的详细信息对象。此对象包含了用户名字串形式表示的角色列表用于后续授权判断过程中的角色匹配操作[^3]。 ```java @Service public class UserDetailsServiceImpl implements UserDetailsService { private final UserRepository userRepository; public UserDetailsServiceImpl(UserRepository userRepository){ this.userRepository = userRepository; } @Override public UserDetails loadUserByUsername(String usernameOrEmail) throws UsernameNotFoundException { Optional<UserEntity> userOptional = userRepository.findByUsernameOrEmail(usernameOrEmail,usernameOrEmail); if (!userOptional.isPresent()){ throw new UsernameNotFoundException("No such a user"); }else{ return new org.springframework.security.core.userdetails.User( userOptional.get().getUsername(), userOptional.get().getPassword(), getAuthority(userOptional.get())); } } private Collection<? extends GrantedAuthority> getAuthority(UserEntity user){ String role=user.getRole(); SimpleGrantedAuthority authority=new SimpleGrantedAuthority(role); List<SimpleGrantedAuthority> authorities=Arrays.asList(authority); return authorities; } } ``` 这段Java代码实现了基于数据库查询获取用户账户数据的功能,并将其转换成适合于Spring Security框架使用的格式以便参与整个认证流程。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值