【问题标题】:Spring RestTemplate POST Query with Headers and Body带有标题和正文的 Spring RestTemplate POST 查询
【发布时间】:2018-03-21 03:41:20
【问题描述】:

我需要使用给定的 API 定义,但我无法在 documentation 找到同时接受标头和请求正文的函数调用。请在此处建议使用 RestTemplate 的哪个功能。

@RequestMapping(value = "/createObject", method = RequestMethod.POST,
        consumes = MediaType.APPLICATION_JSON_VALUE, 
        produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<CreateObjectOutput> createObject(
        @RequestBody CreateObjectInput req) 
{
    CreateObjectOutput out = new CreateObjectOutput();
    ///// Some Code
    return new ResponseEntity<CreateObjectOutput>(out, HttpStatus.OK);
}

【问题讨论】:

  • 我也可以访问 API 定义。请提出定义本身是否有问题。

标签: spring rest


【解决方案1】:
RestTemplate template = new RestTemplate();
CreateObjectInput payload = new CreateObjectInput();

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<CreateObjectOutput> requestEntity = 
     new HttpEntity<>(payload, headers);
CreateObjectOutput response = 
   template.exchange("url", HttpMethod.POST, requestEntity, 
              CreateObjectOutput.class);

【讨论】:

  • HttpEntity 类是当然的答案。我什至检查了 RequestEntity 类,并且 RequestBuilder 特别有趣:)
  • 在一片混乱中最简洁最好的答案。这回答了我的输入和输出问题。我不知道您可以创建 HttpEntity 的模板版本。
【解决方案2】:
//Inject you rest template
@Autowired
RestTemplate restTmplt;

然后在你的方法中使用它。

HttpHeaders header = new HttpHeaders();

//You can use more methods of HttpHeaders to set additional information
header.setContentType(MediaType.APPLICATION_JSON);

Map<String, String> bodyParamMap = new HashMap<String, String>();

//Set your request body params
bodyParamMap.put("key1", "value1");
bodyParamMap.put("key2", "value2");
bodyParamMap.put("key3", "value3");

您可以使用将您的请求正文转换为 JSON 格式的字符串 ObjectMapper 的 writeValueAsString() 方法。

String reqBodyData = new ObjectMapper().writeValueAsString(bodyParamMap);

HttpEntity<String> requestEnty = new HttpEntity<>(reqBodyData, header);

postForEntity() 用于 POST 方法 GET方法的getForEntity()

ResponseEntity<Object> result = restTmplt.postForEntity(reqUrl, requestEnty, Object.class);
        return result;

ObjectMapper 是 Jackson 依赖项 com.fasterxml.jackson.databind.ObjectMapper.ObjectMapper()

根据您期望的响应,它也可以是您自己的类来代替 ResponseEntity Object 类。

例如:

ResponseEntity<Demo> result = restTmplt.postForEntity(reqUrl, requestEnty, Demo.class);

【讨论】:

    【解决方案3】:

    **为 post req 添加的 Api 标头和正文参数: **

    您必须提供 apiKey 和 apiUrl 值才能使用此 POST 请求。提前致谢

    public JSONObject sendRequestToPorichoyUsingRest(String nid,String dob){
        JSONObject jsonObject=null;
        try {
            // create headers
            HttpHeaders headers = new HttpHeaders();
            // set `content-type` header
            headers.setContentType(MediaType.APPLICATION_JSON);
            // set `accept` header
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
            headers.set("x-api-key",apiKey);
            // request body parameters
            Map<String, Object> map = new HashMap<>();
            map.put("national_id",nid);
            map.put("dob",dob);
            // build the request
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(map, headers);
            // send POST request
            ResponseEntity<String> response = restTemplate.postForEntity(apiUrl, entity, String.class);
    
            // check response
            if (response.getStatusCode() == HttpStatus.OK) {
                System.out.println("Request Successful");
                System.out.println(response.getBody());
                JSONParser parser=new JSONParser();
                jsonObject=(JSONObject) parser.parse(response.getBody());
            } else {
                System.out.println("Request Failed");
                System.out.println(response.getStatusCode());
            }
        }catch (Exception e){
            LOGGER.error("Something went wrong when getting data from porichoy "+e);
        }
    
        return jsonObject;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-22
      • 1970-01-01
      • 2018-11-19
      • 1970-01-01
      • 2016-09-07
      • 1970-01-01
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      相关资源
      最近更新 更多