spring-boot - 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 的错误请求错误消息不是描述性的,可以提供帮助
解决方案
您正在发送带有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;
}
}
推荐阅读
- python - Python:在人脸识别中动态保存未知人脸不起作用
- python - 将加密消息从 python 客户端发送到 nodejs 服务器
- catch2 - Catch2 UnorderedEquals 正确用法
- ios - 如何创建一个接受来自用户的输入的 Siri Intent
- c# - 异常:System.UnauthorizedAccessException,消息:对路径“”的访问被拒绝
- php - 我的表格名称为“费用”和“订单”,我想分别获得总计,然后从费用中减去订单总额
- sql - 如何在执行查询时将 T-SQL 查询输出存储在具有当天日期的新表中
- c - 用空格分隔字符串并将其存储在指针数组中
- javascript - 在javascript中禁用Div
- python - 在pandas python中查找特殊位置