SpringCloudSpringCloud

feignclient发送get请求,传递参数为对象。

2018-12-13  本文已影响0人  cuiyaoqiang

feignclient发送get请求,传递参数为对象。此时不能使用在地址栏传递参数的方式,需要将参数放到请求体中(因为jdk原生urlconnecton 不支持get请求请求体传递参数)。

第一步:

修改application.yml中配置feign发送请求使用apache httpclient 而不是默认的jdk UrlConnection

 feign.httpclient.enabled= true

第二步:

pom.xml中增加对apache httpclient的支持。

<!-- 配置feign 发送请求使用 httpclient,而不是java原生 -->

        <dependency>

            <groupId>org.apache.httpcomponents</groupId>

            <artifactId>httpclient</artifactId>

        </dependency>

        <!-- 使用Apache HttpClient替换Feign原生httpclient -->

        <dependency>

            <groupId>com.netflix.feign</groupId>

            <artifactId>feign-httpclient</artifactId>

            <version>8.15.1</version>

        </dependency>

第三步:编写接口类

在ApacheHttpClient中看到默认设置的Content-Type是ContentType.DEFAULT_TEXT,即text/plain; charset=ISO-8859-1, 此时传递对象需要配置为application/json

@FeignClient(name="feign-consumer")

public interface ServiceClient3 {

    /**@param user

    * @return

    */

    @RequestMapping(method = RequestMethod.GET, value = "/test4",consumes="application/json")

    String getInstanceInfo4(User user);

}

第四步:编写接收请求类

    /**Feign发送Get请求时用对象传递参数

    * @param servers

    * @return

    */

    @RequestMapping(value="/test4", method = RequestMethod.GET,consumes="application/json") 

    public String firstDemo4(@RequestBody User u) {

        System.out.println(u);

        return "hello3"+u;

    }

上一篇下一篇

猜你喜欢

热点阅读