問題
在使用SpringCloud時,發現Feign不能發送POST表單請求
注意:在SpringBoot/Cloud環境中,使用的FeignClient,在不做額外設定的情況下,隻能使用MVC的注解,也就是@RequestMapping和@RequestBody或者@RequestParam。
FeignClient 的 接口嘗試以 POST表單發送請求的寫法:
@RequestMapping(value="/someThing/someMethod", method=RequestMethod.POST)
ApiResponse someThing(@RequestParam("name") String value);
在沒有改變預設Encoder的設定的情況下,FeignClient 對于簡單類型的參數,例如String,Integer這些 wrapped primitive types,這種類型将被編碼為form表單參數,即便寫了method=RequestMethod.POST,但是參數沒有出現在Body中,而是在URL上,不符合需求。
解決方案
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form-spring</artifactId>
<version>3.3.0</version>
</dependency>
對應FeignClient用戶端
@FeignClient(name="remoteService",configuration = IRemoteService.FormSupportConfig.class)
public interface IRemoteService {
@RequestMapping(value="/someThing/someMethod",
method=RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
ApiResponse someThing(@RequestBody Map<String, ?> formParams);
}
class FormSupportConfig {
@Bean
public Encoder feignFormEncoder() {
return new SpringFormEncoder();
}
}
}
這樣就可以發送表單請求了。
另一種不需要引入依賴的方法
List<NameValuePair> nvps = new ArrayList<>();
nvps.add(new BasicNameValuePair("key1", key1.toString()));
nvps.add(new BasicNameValuePair("key2", StringUtils.join(key2, ",")));
nvps.add(new BasicNameValuePair("key3", key3.toString()));
String queryStr = URLEncodedUtils.format(nvps, Consts.UTF_8);
someThing(queryStr);
對應
@RequestMapping(value="/someThing/someMethod",
method=RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
ApiResponse someThing(@RequestBody String formParam);
推翻重來,上面的解決方案有問題
在同時使用表單和 RequestBody 的時候,使用上面的配置會抛異常,
is not a type supported by this encoder
将上面的configuration 改成這個類就沒有問題了
import feign.codec.Encoder;
import feign.form.FormEncoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.cloud.netflix.feign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;
import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;
public class CoreFeignConfiguration {
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
@Bean
@Primary
@Scope(SCOPE_PROTOTYPE)
Encoder feignFormEncoder() {
return new FormEncoder(new SpringEncoder(this.messageConverters));
}
}