【问题标题】:RestTemplate in Java - Not enough variable values available with RestTemplate [duplicate]Java中的RestTemplate-RestTemplate没有足够的变量值[重复]
【发布时间】:2015-10-19 12:11:25
【问题描述】:

我有以下内容:

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

攻击这个方法:

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);
    }

我认为它应该可以工作,但它让我很失望

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: Not enough variable values available to expand 'notification'

为什么?

【问题讨论】:

  • @ESala 你读过第一行吗?您应该阅读问题正文,而不仅仅是标题
  • 我读过,但那些是重复的。我从那里得到了你接受的答案,并用一些 javadoc 和示例完成了它。
  • @ESala 确实,这是重复的,所以我要删除这个问题。
  • 仅供未来读者参考:OP 不接受正确答案。
  • 仅供未来读者参考:我错误地接受了@ESala NON-CORRECT 答案。我的回答奏效了。

标签: java spring spring-mvc url resttemplate


【解决方案1】:

正如您的问题的副本所说,您的网址中有{ }

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

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

restTemplate.postForEntity(url, entity, String.class, notification);

【讨论】:

    【解决方案2】:

    以下行足以让它工作。我摆脱了关键角色,现在它正在工作。

    final String url = "http://DATA/create";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-16
      • 1970-01-01
      • 2016-12-08
      • 1970-01-01
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      相关资源
      最近更新 更多