首页 > 解决方案 > Spring Boot RestTemplate:直接从邮递员复制时出现错误请求

问题描述

所以我有一个 API 请求,我直接从邮递员那里复制详细信息。但是,我收到了一个错误的请求错误。

@Service
public class GraphApiService {

@Bean
public RestTemplate restTemplate() {

    return new RestTemplate();
}
@Autowired
RestTemplate restTemplate;
@Autowired
Constants constants;
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public ResponseEntity<String> getAccessTokenUsingRefreshToken(Credential cred) throws IOException{
    try {

    //https://docs.microsoft.com/en-us/graph/auth-v2-user
    // section 5. Use the refresh token to get a new access token
    String url = "url";
    JSONObject body = new JSONObject();
    body.put("grant_type", "refresh_token");
    body.put("client_id", "clientid");
    body.put("scope","User.Read offline_access Files.Read Mail.Read Sites.Read.All");
    body.put("redirect_uri", "http://localhost");
    body.put("client_secret","secret");
    body.put("refresh_token", "token");
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    HttpEntity<String> request =  new HttpEntity<String>(body.toString(), headers);
   ResponseEntity<String> response=  restTemplate.postForEntity(url, request,String.class);
   return response;
    }
    catch(HttpClientErrorException  e){
        logger.error(e.getResponseBodyAsString());
        logger.error(e.getMessage());
        return null;
    }

}

我将不胜感激任何帮助。来自 microsoft graph 的错误请求错误消息不是描述性的,可以提供帮助

标签: spring-bootresttemplate

解决方案


您正在发送带有FORM_URLENCODED标头的 JSON 有效负载。您需要检查 API 是否接受 json 有效负载,如果是,则需要将内容类型更改为,application/json或者您可以按如下方式发布表单数据。

public ResponseEntity<String> getAccessTokenUsingRefreshToken(Credential cred) throws IOException{
    try {
        //https://docs.microsoft.com/en-us/graph/auth-v2-user
        // section 5. Use the refresh token to get a new access token
        String url = "url";
        MultiValueMap<String, String> multiValueMap= new LinkedMultiValueMap<String, String>();
        multiValueMap.add("grant_type", "refresh_token");
        multiValueMap.add("client_id", "clientid");
        //.....
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request =  new HttpEntity<>(multiValueMap, headers);
        ResponseEntity<String> response=  restTemplate.postForEntity(url, request, String.class);
        return response;
    }catch(HttpClientErrorException  e){
        logger.error(e.getResponseBodyAsString());
        logger.error(e.getMessage());
        return null;
    }

}

推荐阅读