feignclient發送get請求,傳遞參數為對象


feignclient發送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 ServiceClient {

    /**@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;
	}  

  參考鏈接:

    https://blog.csdn.net/cuiyaoqiang/article/details/81215483

 

上手,運行。。。報錯:Caused by: java.lang.NoSuchMethodError: feign.Response.create(ILjava/lang/String;Ljava/util/Map;Lfeign/Response$Body;)Lfeign/Response;

  參考 https://ask.csdn.net/questions/773444 這個問答,得知需要修改依賴版本

<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-httpclient</artifactId>
    <version>10.1.0</version>
</dependency>

  完美解決

以上操作可用SpringQueryMap注解代替(前提spring cloud2.1.x及以上版本):

  spring cloud項目使用feign的時候都會發現一個問題,就是get方式無法解析對象參數。其實feign是支持對象傳遞的,但是得是Map形式,而且不能為空,與spring在機制上不兼容,因此無法使用。

spring cloud在2.1.x版本中提供了@SpringQueryMap注解,可以傳遞對象參數,框架自動解析,只可惜啊,得是2.1.0以后的版本。
@FeignClient(name="feign-consumer")
public interface ServiceClient {

    @RequestMapping(method = RequestMethod.GET, value = "/test4")
    String getInstanceInfo4(@SpringQueryMap User user);
}

  參考鏈接:

    http://www.itmuch.com/spring-cloud-sum/feign-multiple-params-2/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM