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

使用RestTemplate请求Token时响应体为null的问题求助

问题描述

使用RestTemplate向服务器请求Token时,响应体始终为null,尝试了exchange和postForEntity两种方法结果完全一致。但用Postman发起相同请求时,响应正常且包含正确的Token。相关代码如下:

@Autowired
RestTemplate restTemplate;

private static final String AUTHENTICATION_URL = "http://localhost:8084/api/auth/login";
    
private Disposable token;

@RequestMapping(value = "/TempResp", method = RequestMethod.GET)
public String gethttpResp(@RequestBody LoginDto loginDto) throws JsonProcessingException {
    String username = loginDto.getUsername();
    String password = loginDto.getPassword();
    String response = null;
    try {
            // create user authentication object
            User authenticationUser = getAuthenticationUser(loginDto);
            // convert the user authentication object to JSON
            String authenticationBody = getBody(authenticationUser);
            // create headers specifying that it is JSON request
            HttpHeaders authenticationHeaders = getHeaders();
            HttpEntity<String> authenticationEntity = new HttpEntity<String> 
                    (authenticationBody,authenticationHeaders);
            RestTemplate restTemplate = new RestTemplate();
//          HttpHeaders headers = new HttpHeaders();
//          headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
//          headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            // Authenticate User and get JWT
            ResponseEntity<ResponseToken> authenticationResponse = 
                    restTemplate.postForEntity(AUTHENTICATION_URL,
                    authenticationEntity, ResponseToken.class);
                
            // if the authentication is successful      
            System.out.println(authenticationResponse.getStatusCode().equals(HttpStatus.OK));
            // if the authentication is successful      
            if (authenticationResponse.getStatusCode().equals(HttpStatus.OK)) {
                String token = "Bearer " + authenticationResponse.getBody().getToken();
                System.out.println("Token is " + token);

            }
            
                        
    } catch(Exception ex) {
        System.out.println("exception");
        

    }
    return response;
    
}

可能的原因及解决方案

1. 重复创建RestTemplate实例

代码中已经通过@Autowired注入了Spring容器管理的RestTemplate,但方法内又手动新建了实例。手动创建的实例没有加载容器中配置的消息转换器、拦截器等,会导致响应体无法正确反序列化。

解决:
删除手动创建的代码,直接使用注入的Bean:

// 移除该行:RestTemplate restTemplate = new RestTemplate();
ResponseEntity<ResponseToken> authenticationResponse = 
        restTemplate.postForEntity(AUTHENTICATION_URL, authenticationEntity, ResponseToken.class);

2. ResponseToken类反序列化不匹配

服务器返回的JSON字段与ResponseToken类的属性无法映射,会导致反序列化失败,响应体为null。

检查点:

  • 确认类的属性名与服务器返回的JSON字段名完全一致(区分大小写),如果字段名不一致,添加@JsonProperty("字段名")注解指定映射关系。
  • 确保类有公开的无参构造函数(Jackson默认要求)。
  • 确保属性有对应的getter方法(如getToken())。

3. 请求头或请求体格式不符

需要确认getHeaders()方法是否正确设置了Content-Type: application/json,同时对比authenticationBody的JSON结构与Postman发送的请求体是否完全一致。

验证示例:
检查getHeaders()的实现是否正确:

private HttpHeaders getHeaders() {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    return headers;
}

4. 异常信息未输出

代码中捕获异常后仅打印"exception",无法定位具体错误。建议打印完整异常堆栈:

catch(Exception ex) {
    ex.printStackTrace(); // 输出详细异常信息,快速定位问题
}

5. 消息转换器缺失

如果注入的RestTemplate未配置Jackson消息转换器,可能无法处理JSON响应。可以在RestTemplate的Bean配置中添加转换器:

@Bean
public RestTemplate restTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setObjectMapper(new ObjectMapper());
    restTemplate.getMessageConverters().add(converter);
    return restTemplate;
}

内容的提问来源于stack exchange,提问作者Jorge

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 08:51:03