問(wèn)題
在使用SpringCloud時(shí),發(fā)現(xiàn)Feign不能發(fā)送POST表單請(qǐng)求
注意:在SpringBoot/Cloud環(huán)境中,使用的FeignClient,在不做額外設(shè)置的情況下,只能使用MVC的注解,也就是@RequestMapping和@RequestBody或者@RequestParam。
FeignClient 的 接口嘗試以 POST表單發(fā)送請(qǐng)求的寫法:
@RequestMapping(value="/someThing/someMethod", method=RequestMethod.POST)
ApiResponse someThing(@RequestParam("name") String value);
在沒(méi)有改變默認(rèn)Encoder的設(shè)置的情況下,F(xiàn)eignClient 對(duì)于簡(jiǎn)單類型的參數(shù),例如String,Integer這些 wrapped primitive types,這種類型將被編碼為form表單參數(shù),即便寫了method=RequestMethod.POST,但是參數(shù)沒(méi)有出現(xiàn)在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>
對(duì)應(yīng)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();
}
}
}
這樣就可以發(fā)送表單請(qǐng)求了。
另一種不需要引入依賴的方法
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);
對(duì)應(yīng)
@RequestMapping(value="/someThing/someMethod",
method=RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
ApiResponse someThing(@RequestBody String formParam);
推翻重來(lái),上面的解決方案有問(wèn)題
在同時(shí)使用表單和 RequestBody 的時(shí)候,使用上面的配置會(huì)拋異常,
is not a type supported by this encoder
將上面的configuration 改成這個(gè)類就沒(méi)有問(wèn)題了
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));
}
}