Add my custom http header to Spring RestTemplate request / extend RestTemplate

后端 未结 3 686
名媛妹妹
名媛妹妹 2020-12-13 17:50

My current code:

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Mall[] m         


        
3条回答
  •  生来不讨喜
    2020-12-13 18:18

    You can pass custom http headers with RestTemplate exchange method as below.

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(new MediaType[] { MediaType.APPLICATION_JSON }));
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("X-TP-DeviceID", "your value");
    
    HttpEntity entityReq = new HttpEntity(request, headers);
    
    RestTemplate template = new RestTemplate();
    
    ResponseEntity respEntity = template
        .exchange("RestSvcUrl", HttpMethod.POST, entityReq, RestResponse.class);
    

    EDIT : Below is the updated code. This link has several ways of calling rest service with examples

    RestTemplate restTemplate = new RestTemplate();
    
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("X-TP-DeviceID", "your value");
    
    HttpEntity entity = new HttpEntity("parameters", headers);
    
    ResponseEntity respEntity = restTemplate.exchange(url, HttpMethod.POST, entity, Mall[].class);
    
    Mall[] resp = respEntity.getBody();
    

提交回复
热议问题