Search code examples
springrestcontent-typeresttemplate

Setting request header content-type to json in Spring Framework resttemplate


I'm learning Spring Framework to create a client of a REST web service that uses basic authentication and exchanges JSON. After much searching on the web, I wrote some code that worked (below), but now I'm getting an "Unsupported Media Type" error because the requests are sent with Content-Type text/plain rather than application/json. I've found nothing on the web that shows how to set Content-Type in the request header (without getting completely lost in the weeds). My code is:

import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

...

BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("login", "password"));
HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);

RestTemplate restTemplate = new RestTemplate(requestFactory);
String url = "http://host:8080/path/";
String postBody = getPostInput("filename");
jsonString = restTemplate.postForObject(path, postBody, String.class);

Any guidance would be greatly appreciated.

Thanks, George


Solution

  • you can try using any method from below code

    1

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    
    HttpEntity<String> entity = new HttpEntity<String>(postBodyJson ,headers);
    restTemplate.put(uRL, entity);
    

    2

    RequestEntity<String> requestEntity = RequestEntity .post(new URL(attributeLookupUrl).toURI()) .contentType(MediaType.APPLICATION_JSON) .body(postBodyJson); 
    restTemplate.exchange(requestEntity, responseClass);
    

    3

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    
    // if you need to pass form parameters in request with headers.
    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    map.add("username", userName);
    map.add("password", password);
    
    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
    ResponseEntity<TokenVO> responses = restTemplate.postForEntity(URL, request, responseClass);