Java 中的 RestTemplate - RestTemplate 没有足够的变量值

sta*_*man 0 java url spring spring-mvc resttemplate

我有以下内容:

final String notification = "{\"DATA\"}";
final String url = "http://{DATA}/create";
ResponseEntity<String> auth = create(address, name, psswd, url);
Run Code Online (Sandbox Code Playgroud)

攻击该方法:

private ResponseEntity<String> create(final String address, final String name,
                                                          final String newPassword, final String url) {
        final Map<String, Object> param = new HashMap<>();
        param.put("name", name);
        param.put("password", newPassword);
        param.put("email", address);

        final HttpHeaders header = new HttpHeaders();

        final HttpEntity<?> entity = new HttpEntity<Object>(param, header);

        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.postForEntity(url, entity, String.class);
    }
Run Code Online (Sandbox Code Playgroud)

我认为它应该有效,但它让我

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: Not enough variable values available to expand 'notification'
Run Code Online (Sandbox Code Playgroud)

为什么?

ESa*_*ala 5

正如您问题的重复部分所说,您{ }的网址中有。

Spring 会尝试填充它{notification},但由于你不提供它,所以它失败了Not enough variable values available to expand 'notification'

您只需要传递通知字符串,以便 Spring 可以正确构建 URL。

这是该方法的javadoc

public <T> ResponseEntity<T> postForEntity(String url,
                                           Object request,
                                           Class<T> responseType,
                                           Object... uriVariables)
                                    throws RestClientException
Parameters:
    url - the URL
    request - the Object to be POSTed, may be null
    responseType - the class of the response
    uriVariables - the variables to expand the template
Run Code Online (Sandbox Code Playgroud)

因此,您需要将通知字符串作为第四个参数传递,如下所示:

restTemplate.postForEntity(url, entity, String.class, notification);
Run Code Online (Sandbox Code Playgroud)