让Feign支持post方法的表单提交

在使用post方法时,feign默认是不支持表单提交的,即前端传参给复杂对象,参数会丢失,默认是通过application/json的方式

但是,可以通过如下配置,让feign支持post方法的表单提交:

package com.fast.fast.common.feign.config;

import feign.RequestInterceptor;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Feign配置类
 *
 * @author lyf
 * @date 2022/01/01 00:00 周六
 **/
@RequiredArgsConstructor
@AutoConfiguration
public class FeignConfig {

    private final ObjectFactory<HttpMessageConverters> messageConverters;

    /**
     * Feign的form编码器,让Feign支持form表单提交
     *
     * @return
     */
    @Bean
    public Encoder feignFormEncoder() {
        return new SpringFormEncoder(new SpringEncoder(messageConverters));
    }
}
package com.fast.fast.upms.api.feign;

import com.fast.fast.common.base.constant.ServiceNameConstants;
import com.fast.fast.common.base.vo.Result;
import com.fast.fast.upms.api.entity.SysUser;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * description
 *
 * @author lyf
 * @date 2022/6/9 14:03 周四
 **/
@FeignClient(name = ServiceNameConstants.UMPS_SERVICE, path = "sysUser")
public interface SysUserFeign {

    /**
     * 根据用户名和密码获取
     *
     * @param sysUser
     * @return
     */
    @PostMapping(value = "getByUsernameAndPwd", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    Result<SysUser> getByUsernameAndPwd(SysUser sysUser);

}

注意,一定要加上consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE

形参sysUser前不能加入@RequestBody注解

经实践,这只是增强,不影响feign的原有功能

经验分享 程序员 微信小程序 职场和发展