使用JSON有效负载的RestTemplate for GET请求

问题描述 投票:0回答:1

我正在尝试为GET方法创建测试单元,该方法需要JSON有效负载才能根据JSON中提供的数据获取结果。

我试过了:

   User user = new User();
   user.setUserId(userId);

   ResponseEntity<User> getResponse = restTemplate.exchange(getRootUrl() + "/getUser", HttpMethod.GET, user, User.class);

    assertNotNull(getResponse);
    assertEquals(getResponse.getStatusCode(), HttpStatus.OK);

但它在exchange上为user抛出一个错误,该对象不合适。

java json spring spring-boot resttemplate
1个回答
1
投票

method documentation非常简单

对给定的URI模板执行HTTP方法,将给定的请求实体写入请求,并将响应作为ResponseEntity返回。使用给定的URI变量(如果有)扩展URI模板变量。

指定者:接口RestOperations中的exchange参数:url - URL方法 - HTTP方法(GET,POST等)requestEntity - 写入请求的实体(头和/或主体)可能为null)responseType - 类型返回值uriVariables - 要在模板中展开的变量

你需要将用户改为HttpEntity

  HttpHeaders headers = new HttpHeaders();
  headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
  JSONObject parm = new JSONObject();
   parm.put("user", user);
   HttpEntity<JSONObject> entity = new HttpEntity<JSONObject>(parm, headers);
© www.soinside.com 2019 - 2024. All rights reserved.