注意:本文讲的是原生feign,不是结合spring使用feign
- 场景描述
在开发的时候遇到一个问题:由于种种原因,需要使用原生feign发起一个post请求,请求体是json格式。
- 解决方案
见 https://github.com/OpenFeign/feign 的 readme 中 Encoders 部分
- 测试
先启一个服务,代码很简单
@PostMapping(value = "/address/create")
@ResponseBody
public String createAddress(@RequestBody Address address) {
System.out.println(address.getCountry() + "-----" + address.getProvince());
return "OK";
}
Address 类
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Address {
private String country;
private String province;
}
上面是服务端的代码,下面看一下客户端的代码
定义 feign 客户端,这里边有两个方法,分别用于测试上图中说的两种情况
public interface AddressClient {
@RequestLine("POST /address/create")
@Headers("Content-Type: application/json")
String createAddress(String content);
@RequestLine("POST /address/create")
@Headers("Content-Type: application/json")
String createAddress(Address address);
}
开始测试
public class FeignTest {
@Test
public void test01() {
AddressClient addressClient =
Feign.builder().target(AddressClient.class, "http://localhost:8082");
String ok =
addressClient.createAddress("{\"country\": \"china\", \"province\": \"nanjing\"}");
System.out.println("test01 " + ok);
}
@Test
public void test02() {
AddressClient addressClient = Feign.builder().encoder(new GsonEncoder())
.target(AddressClient.class, "http://localhost:8082");
Address address = new Address("china", "beijing");
String ok = addressClient.createAddress(address);
System.out.println("test02 " + ok);
}
}
查看测试结果