java - RestTemplate 的错误请求-> postForObject (Spring Boot)
问题描述
我在一件简单的事情上遇到了一些麻烦。
我正在尝试向其他 REST 服务发送请求
//getting restTemplate from RestTemplateBuilder.build()
//endpoint and rest of variables came in properties
Map<String, String> map = new HashMap<>();
map.put("app", app);
map.put("username", username);
map.put("password", password);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
String token = restTemplate.postForObject(loginEndpoint, headers, String.class, map);
我收到:
Unexpected error occurred in scheduled task.
org.springframework.web.client.HttpClientErrorException: 400 Bad Request
奇怪的是,当我使用简单的 CURL 调用并且工作顺利时。
已经检查了变量和端点,它是正确的。
解决方案
在这种情况下,端点必须在端点 url 上有适当的占位符。
我用这个方法做起来很容易:
private String placeHolders(Map<String, String> values){
String response = "?";
boolean first = true;
for(Map.Entry<String, String> entry:values.entrySet()){
if(first){
first = false;
}else{
response+="&";
}
response+=entry.getKey()+"="+entry.getValue();
}
return response;
}
现在的电话是:
String token = restTemplate.postForObject(loginEndpoint+placeHolders, headers, String.class, map);
推荐阅读
- swift - 从另一个视图控制器访问文本字段并传递数据
- cplex - 每周目标函数 - 帮助编写代码 - CPLEX
- python - 使用 Django RestFramework 推送通知 React Native Expo
- dialogflow-es - 在 google home mini 中进行测试时,Dialogflow 代理的响应不同
- python - 如何在知道请求 url 和标头的情况下获取 api 的 url
- java - 在 Java 中,如何将 LocalDate 和时间格式的字符串加入到 LocalDateTime 的一个可观察属性中?
- python - 如何使用python在同一列中逐行计算值直到每60分钟
- pandas - 熊猫 - 组合
- php - the_post_navigation() 中的最后一篇文章未显示标题
- laravel - php artisan migrate 不适用于 Laravel5.4 中的 XAMP