سؤال

This is my URL: https://api.something.json

I need to add the following headers to the request.

1) Accept: application/json

2) x-api-key: randomKey

I need to add few parameters to the request too. Such as Name and ID

Then I need to make a GET request.

I went through this link here, it says how to make a request with uri variables, but could not find how to add headers to the request. http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/web/client/RestTemplate.html#getForObject(java.lang.String, java.lang.Class, java.lang.Object...)

I am interested in knowing how to add the headers to the request. Thanks.

هل كانت مفيدة؟

المحلول

You need to use one of the exchange(..) methods. Create a MultiValueMap to hold your headers and pass it to the call

MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("x-api-key", "randomKey");

HttpEntity<Void> entity = new HttpEntity<>(headers);
entity.getHeaders().setContentType(MediaType.APPLICATION_JSON);

YourResponseType response = restTemplate.exchange(url, HttpMethod.GET, entity, YourResponseType.class);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top