You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中如何用@PathVariable传递TMDB电影ID并构建正确URI

问题解决指南

核心问题梳理

  1. URI构建错误:使用port(movieid)是错误用法,该方法用于设置HTTP端口,而非添加路径参数。正确做法是将电影ID作为路径段拼接至URL。
  2. Authorization头格式错误:TMDB认证头需遵循Bearer {API_KEY}格式,而非直接拼接字符串。
  3. DTO结构不匹配:TMDB电影详情API返回单个电影对象,而非包含results数组的结构,原DTO会导致反序列化失败。
  4. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 06:05:59