Spring Boot中如何用@PathVariable传递TMDB电影ID并构建正确URI
问题解决指南
核心问题梳理
- URI构建错误:使用
port(movieid)是错误用法,该方法用于设置HTTP端口,而非添加路径参数。正确做法是将电影ID作为路径段拼接至URL。 - Authorization头格式错误:TMDB认证头需遵循
Bearer {API_KEY}格式,而非直接拼接字符串。 - DTO结构不匹配:TMDB电影详情API返回单个电影对象,而非包含
results数组的结构,原DTO会导致反序列化失败。 - RestTemplate实例化不当:每次方法调用新建
RestTemplate会造成资源浪费,应配置为Spring Bean注入使用。
修正后的代码实现
1. Service层代码修正
@Service public class MovieSearchService { @Value("${tmdb.api}") private String tmdbKey; private final String movieDetailUrl = "https://api.themoviedb.org/3/movie"; private final RestTemplate restTemplate; // 注入RestTemplate,替代每次新建实例 public MovieSearchService(RestTemplate restTemplate) { this.restTemplate = restTemplate; } public MovieSearchDetailDto movieSearchDetailApi(int movieId) { HttpHeaders httpHeaders = new HttpHeaders(); // 修正Authorization头格式 httpHeaders.set("Authorization", "Bearer " + tmdbKey); HttpEntity<String> httpEntity = new HttpEntity<>(httpHeaders); // 正确构建URI:通过pathSegment添加电影ID路径参数 URI targetUrl = UriComponentsBuilder .fromUriString(movieDetailUrl) .pathSegment(String.valueOf(movieId)) .queryParam("language", "ko-KR") // 使用Bearer认证时,无需重复传递api_key查询参数 .build() .encode(StandardCharsets.UTF_8) .toUri(); ResponseEntity<MovieSearchDetailDto> result = restTemplate.exchange( targetUrl, HttpMethod.GET, httpEntity, MovieSearchDetailDto.class ); return result.getBody(); } }
2. DTO结构修正
@Getter @AllArgsConstructor @NoArgsConstructor @Builder public class MovieSearchDetailDto { private int id; private String poster_path; private String release_date; private String title; private String overview; }
3. RestTemplate配置类(可选,也可在启动类中配置)
@Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }
4. 启动类修正(移除Service上的@SpringBootApplication)
确保启动类独立存在:
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) public class JoyitApplication { public static void main(String[] args) { SpringApplication.run(JoyitApplication.class, args); } }
额外说明
- TMDB的Bearer认证与
api_key查询参数二选一即可,推荐使用Bearer头认证。 - DTO字段名需与TMDB返回的JSON字段严格匹配(原DTO中的
moive_id为拼写错误,应改为id)。 - 可添加
RestClientException捕获逻辑,处理API调用失败场景。
内容的提问来源于stack exchange,提问作者sera
相关产品推荐
相关产品推荐

