Using @Headers with dynamic values in Feign client + Spring Cloud (Brixton RC2)

SpringSpring CloudSpring Cloud-Netflix

Spring Problem Overview


Is it possible to set dynamic values to a header ?

@FeignClient(name="Simple-Gateway")
interface GatewayClient {
	@Headers("X-Auth-Token: {token}")
	@RequestMapping(method = RequestMethod.GET, value = "/gateway/test")
	    String getSessionId(@Param("token") String token);
	}

Registering an implementation of RequestInterceptor adds the header but there is no way of setting the header value dynamically

@Bean
    public RequestInterceptor requestInterceptor() {
		
		return new RequestInterceptor() {
			
			@Override
			public void apply(RequestTemplate template) {
				
				template.header("X-Auth-Token", "some_token");
			}
		};
	} 

I found the following issue on github and one of the commenters (lpborges) was trying to do something similar using headers in @RequestMapping annotation.

https://github.com/spring-cloud/spring-cloud-netflix/issues/288

Kind Regards

Spring Solutions


Solution 1 - Spring

The solution is to use @RequestHeader annotation instead of feign specific annotations

@FeignClient(name="Simple-Gateway")
interface GatewayClient {    
    @RequestMapping(method = RequestMethod.GET, value = "/gateway/test")
    String getSessionId(@RequestHeader("X-Auth-Token") String token);
}

Solution 2 - Spring

The @RequestHeader did not work for me. What did work was:

@Headers("X-Auth-Token: {access_token}")
@RequestLine("GET /orders/{id}")
Order get(@Param("id") String id, @Param("access_token") String accessToken);

Solution 3 - Spring

@HeaderMap,@Header and @Param didn't worked for me, below is the solution to use @RequestHeader when there are multiple header parameters to pass using FeignClient

@PostMapping("/api/channelUpdate")
EmployeeDTO updateRecord(
	  @RequestHeader Map<String, String> headerMap,
	  @RequestBody RequestDTO request);

code to call the proxy is as below:

Map<String, String> headers = new HashMap<>();
headers.put("channelID", "NET");
headers.put("msgUID", "1234567889");
ResponseDTO response = proxy.updateRecord(headers,requestDTO.getTxnRequest());

Solution 4 - Spring

I have this example, and I use @HeaderParam instead @RequestHeader :

import rx.Single;

import javax.ws.rs.Consumes;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;


@Consumes(MediaType.APPLICATION_JSON)
public interface  FeignRepository {

  @POST
  @Path("/Vehicles")
  Single<CarAddResponse> add(@HeaderParam(HttpHeaders.AUTHORIZATION) String authorizationHeader, VehicleDto vehicleDto);

}

Solution 5 - Spring

You can use HttpHeaders.

@PostMapping(path = "${path}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<?> callService(@RequestHeader HttpHeaders headers, @RequestBody Object object);

private HttpHeaders getHeaders() {
  HttpHeaders headers = new HttpHeaders();

  headers.add("Authorization", "1234");
  headers.add("CLIENT_IT", "dummy");
  return headers;
}

Solution 6 - Spring

I use @HeaderMap as it seems very handy if you are working with Open feign. Using this way you can pass header keys and values dynamically.

@Headers({"Content-Type: application/json"})
public interface NotificationClient {

    @RequestLine("POST")
    String notify(URI uri, @HeaderMap Map<String, Object> headers, NotificationBody body);
}

Now create feign REST client to call the service end point, create your header properties map and pass it in method parameter.

NotificationClient notificationClient = Feign.builder()
    .encoder(new JacksonEncoder())
    .decoder(customDecoder())
    .target(Target.EmptyTarget.create(NotificationClient.class));
	
Map<String, Object> headers = new HashMap<>();
headers.put("x-api-key", "x-api-value");
			
ResponseEntity<String> response = notificationClient.notify(new URI("https://stackoverflow.com/example"), headers, new NotificationBody());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHasnainView Question on Stackoverflow
Solution 1 - SpringHasnainView Answer on Stackoverflow
Solution 2 - SpringCarlos Alberto SchneiderView Answer on Stackoverflow
Solution 3 - SpringvijayView Answer on Stackoverflow
Solution 4 - SpringOscar Raig ColonView Answer on Stackoverflow
Solution 5 - SpringDavid SalazarView Answer on Stackoverflow
Solution 6 - SpringMuhammad UsmanView Answer on Stackoverflow