Send form data using Feign in Spring Boot

Feign acts as a proxy to hide the actual services. The user has the impression that it's getting the response from only one service. But behind the scene Feign acts on behalf of the user and requests the corresponding services to get or set data. In this article I will explain how we can send form data using Feign to an actual service.
Feign works with Netflix Zuul. To enable Feign, add the following dependencies in your pom file.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
Then add the annotations as below on your application.
@EnableFeignClients
@EnableZuulProxy
public class FeignApplication{
}
We can now add our Feign interceptor declaratively as below.
@FeignClient(name="actual-service",configuration = CoreFeignConfiguration.class)
public interface FeignInterceptor{
@RequestMapping(method = RequestMethod.POST,value="/path/to/service",
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
@Headers("Content-Type: application/x-www-form-urlencoded")
sendData(@RequestBody Map<String, ?> formParams);
}
import feign.form.FormEncoder;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.cloud.netflix.feign.support.SpringEncoder;
@Configuration
public class CoreFeignConfiguration {
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
@Bean
FormEncoder feignFormEncoder() {
return new FormEncoder(new SpringEncoder(this.messageConverters));
}
}
Using @FeignClient annotation, we can declare that we want to connect to the service with name "actual-service" and want to use the configuration as defined in the CoreFeignConfiguration class.
The formParams variable is just a Map of key value pair which is retrieved from the Form data in the Controller as shown below.
@RequestMapping(method = RequestMethod.POST,value = "/form-data")
public List<String> authenticateMe(@RequestBody MyForm myForm){
feignInterceptor.sendData(mapFromMyForm(myForm));
}
We can write the method mapFromMyForm to convert the myForm to a Map of key value pair. That's all we need to successfully send Form Data using Feign.
Sharing is Caring!
RECOMMENDED POSTS FOR YOU