带有标头和正文的 Spring RestTemplate POST 查询

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

我需要使用给定的 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);
}
spring rest
4个回答
31
投票
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);

8
投票
//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 方法 getForEntity() 用于 GET 方法

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

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

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

例如:

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

2
投票

**为帖子请求添加了 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;
}

0
投票
public ExternalAPIUser SendUser(ExternalAPIUser externalAPIUser) {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.set("User", "Karan");
    HttpEntity<ExternalAPIUser> http = new HttpEntity<>(externalAPIUser, httpHeaders);
    ResponseEntity<ExternalAPIUser> externalAPIUserResponseEntity = restTemplate.exchange("http://localhost:3000/save",
            HttpMethod.POST, http, ExternalAPIUser.class);
    ExternalAPIUser e = externalAPIUserResponseEntity.getBody();
    if (e != null) {
        return e;
    } else {
        return null;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.