调用外部平台http接口,Post请求,url 为路径带有参数的形式:
http://xxxxxx.com/openApi/auth/getUserAuth?version=v1.0
使用 Retrofit 框架(本文使用的2.6.2版本)发送Post请求,可以在 @Post 注解中直接带上参数,如下:
@POST("auth/getUserAuth?version=v1.0")
Call<McgjResponse<UserAuthResponseDTO>> getUserAuth(@Body UserAuthRequest userAuthRequest);
因为初次使用 Retrofit 框架,所以自己启动Spring服务模拟外部平台接口,发现之前一直都在@PostMapping中定义路径,还没怎么写过带参数的,导致写错了,报 404错误,记录一下下。先说正确写法:
正确写法:
@PostMapping(value ="/authorize/addRecord",params = "version=v1.0")
public McgjResponse<UserAuthResponseDTO> test(){
其实@RequestMapping、@GetMapping、@PostMapping 三个注解都可以指定请求Header、请求path、以及请求params。
@RequestMapping("/foo") 等价于 @RequestMapping(path="/foo")
/**
* The primary mapping expressed by this annotation.
* <p>In a Servlet environment this is an alias for {@link #path}.
* For example {@code @RequestMapping("/foo")} is equivalent to
* {@code @RequestMapping(path="/foo")}.
* <p>In a Portlet environment this is the mapped portlet modes
* (i.e. "EDIT", "VIEW", "HELP" or any custom modes).
* <p><b>Supported at the type level as well as at the method level!</b>
* When used at the type level, all method-level mappings inherit
* this primary mapping, narrowing it for a specific handler method.
*/
@AliasFor("path")
String[] value() default {};
所以平常在括号中直接写,只是指定了 path。如果错误地把参数写到请求 path 中,则会报 HTTP 404 错误,如下错误写法:
错误写法:
//错误写法
@PostMapping(value ="/auth/getUserAuth?version=v1.0")
public McgjResponse<UserAuthResponseDTO> test(){
总结:这三个注解平时用的是如此之多,却如此不熟悉,实在不应该!