简体   繁体   English

用于JSON有效负载的GET请求的RestTemplate

[英]RestTemplate for GET request with JSON payload

I'm trying to create test unit for GET method which requires JSON payload to get result based on provided data in JSON. 我正在尝试为GET方法创建测试单元,该方法需要JSON有效负载才能基于JSON中提供的数据获取结果。

I have tried that: 我已经尝试过:

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

but it throws an error on exchange for user that object is not suitable. 但是在与user exchange该对象不合适时会引发错误。

the method documentation is pretty straightforward 方法文档非常简单

Execute the HTTP method to the given URI template, writing the given request entity to the request, and returns the response as ResponseEntity. 对给定的URI模板执行HTTP方法,将给定的请求实体写入请求,然后将响应作为ResponseEntity返回。 URI Template variables are expanded using the given URI variables, if any. 使用给定的URI变量(如果有)扩展URI模板变量。

Specified by: exchange in interface RestOperations Parameters: url - the URL method - the HTTP method (GET, POST, etc) requestEntity - the entity (headers and/or body) to write to the request may be null) responseType - the type of the return value uriVariables - the variables to expand in the template 指定者:接口RestOperations中的exchange参数:url-URL方法-HTTP方法(GET,POST等)requestEntity-要写入请求的实体(标头和/或主体)可以为null)responseType-类型返回值uriVariables-模板中要扩展的变量

you need change user to HttpEntity 您需要将用户更改为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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM