简体   繁体   中英

How can I pass headers using RestTemplate?

In my method I initially used RestTemplate postForObject method to post request to an endpoint. Now I have to add default OAuth token and pass it as Post request. Is there any way I can pass both request as well as Default Header as part of POST request by using postForObject ?

Initiall I used below postForObject

 String result = restTemplate.postForObject(url, request, String.class);

I am looking for something like below

             restTemplate.exchange(url,HttpMethod.POST,getEntity(),String.class );

Here is my code

    private final String url;
        private final MarkBuild header;

    public DataImpl(@Qualifier(OAuth) MarkBuild header,RestTemplate restTemplate) {
               this.restTemplate= restTemplate;
                this.header = header;
    }

    public void postJson(Set<String> results){
        try {
             Map<String, String> requestBody = new HashMap<>();
             requestBody.put("news", "data");
              JSONObject jsonObject = new JSONObject(requestBody);

             HttpEntity<String> request = new HttpEntity<String>(jsonObject.toString(), null);

            String result = restTemplate.postForObject(url, request, String.class);
        } 
    }

Below is getHttpEntity which I want to pass with Post request


    private HttpEntity getHttpEntity(Set <String>results) {
          return new HttpEntity<>( null, getHttpHeaders() );
    }

    private HttpHeaders getHttpHeaders() {
        return header.build();
    }
}

Is there any way I can pass both request as well as Default Header as part of POST request by using postForObject?

Yes, there is a way to do that, I can give a basic example:

HttpHeaders lHttpHeaders = new HttpHeaders();
lHttpHeaders.setContentType( MediaType.APPLICATION_JSON );//or whatever it's in your case
String payload="<PAYLOAD HERE>"
try
{
    String lResponseJson = mRestTemplate.postForObject( url, new HttpEntity<Object>( payload, lHttpHeaders ), String.class);
    return lResponseJson;
}
catch( Exception lExcp )
{
    logger.error( lExcp.getMessage(), lExcp );
}

Let me know if this doesn't work!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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