关键词
- Java
- OpenFeign、@QueryMap
- HttpURLConnection、doOutput、connection.setDoOutput(true)
- GET变POST
背景
相信在微服务架构下做过开发的同学对“跨服务调用”都是比较熟悉的,很多时候我们可能会选择HTTP接口调用的方式来进行服务间调用。OpenFeign作为一种开源的“声明式”HTTP客户端受到了许多开发者的青睐,毕竟只需要简单写个接口,加两个注解就能使用,何乐而不为呢?
正确地使用框架固然能极大提高我们的开发效率,但框架毕竟帮我们屏蔽了太多底层的逻辑,知道得越少,我们就越有可能犯错。
对于使用OpenFeign来说,笔者就踩过一个初看让人很摸不着头脑的坑…
先来看一个简单的测试代码:
- 参数类型定义
@Data
@AllArgsConstructor
@ToString
public class TestParam {
private int id;
private String name;
}
- 服务端接口
@RestController
@RequestMapping("/feignTest")
public class TestController {
@GetMapping
public String feignGetTest(TestParam testParam) {
System.out.println("---- GET ----");
System.out.println("param: " + testParam);
return "response for GET request, your param is " + testParam;
}
@PostMapping
public String feignPostTest(@RequestBody TestParam param) {
System.out.println("---- POST ----");
System.out.println("param: " + param);
return "response for POST request, your param is: " + param;
}
}
- OpenFeign客户端测试
public class Test {
interface TestHttpClient {
@RequestLine("GET /feignTest")
@Headers(value = "Content-Type:application/json")
String simpleHttpGetTest(TestParam urlParam);
@RequestLine("POST /feignTest")
@Headers(value = "Content-Type:application/json")
String simpleHttpPostTest(TestParam postBody);
}
public static void main(String[] args) {
TestHttpClient testClient