jlp
jlp

Reputation: 1706

Is there a way to add multiple headers when using Feign Client

I have a Feign client to access to an createUser endpoint that requires two headers: username and password. I know how to add one header, but how do I add two headers to the request?

@FeignClient(name = "client", url = "https://abc.abc.com/user/", configuration = FeignClientConfig.class)
public interface MyFeignClient {

@Headers("username_header: {username}")  // how do I add "password" here.
@PostMapping(value = "v1/users")
void createUser((@Param("username") String username, User userRequest);

}

Update: Now based on the answer below, I changed the interface body to:

@Headers({"username_header: {username}", "password_header: {password}"}) 
@PostMapping(value = "v1/users")
void createUser(@Param("username") String username, 
                @Param("password") String password,
                User userRequest);

And the code that calls it is:

feignClient.createUser("me", "123", userObj);

Then I am getting an error:

 org.springframework.beans.factory.BeanCreationException: Error creating bean,
 nested exception is java.lang.IllegalStateException: Method has too many Body parameters: 
 feignClient.createUser(java.lang.String,java.lang.String, User)

Upvotes: 6

Views: 17167

Answers (3)

Mohit Hurkat
Mohit Hurkat

Reputation: 416

@RequestLine("POST /v1/users")
@Body("{userBody}")
Response createUser(@HeaderMap Map headerMap, @Param(value = "userBody") String userBody);

Updated

@RequestLine("POST /v1/users") 
Response createUser(String userBody, @HeaderMap Map headerMap);

Upvotes: 0

Paulo Pedroso
Paulo Pedroso

Reputation: 3705

I know it may be late but I am hopping to help others.

What has worked for me:

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;

@PostMapping(path = "${service-uri}", consumes = MediaType.APPLICATION_JSON_VALUE)
    String callService(@RequestBody MyBodyClass body, @RequestParam Integer param01, @RequestParam String param02, @RequestHeader Map<String, String> headerMap);

The solution proposed with @HeaderMap doesn't work, apparently because this class is from feign package (import feign.HeaderMap).

Upvotes: 2

James Gawron
James Gawron

Reputation: 969

Headers accepts String[] for value ... So

    @Headers({ "username: {username}", "password: {password}" })

Should do the trick

Upvotes: 0

Related Questions