首页 > 解决方案 > 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 调用并且工作顺利时。

已经检查了变量和端点,它是正确的。

标签: javaspring-resttemplate

解决方案


在这种情况下,端点必须在端点 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);

推荐阅读