idtitlesidebar_label
    http_method
    HTTP Method
    HTTP Method

    使用POST方式

    1. public interface MyClient {
    2. /**
    3. * 通过 @Request 注解的 type 参数指定 HTTP 请求的方式。
    4. */
    5. @Request(
    6. url = "http://localhost:8080/hello",
    7. type = "POST"
    8. )
    9. String simplePost();
    10. /**
    11. * 使用 @Post 注解,可以去掉 type = "POST" 这行属性
    12. */
    13. @Post("http://localhost:8080/hello")
    14. String simplePost();
    15. /**
    16. * 使用 @PostRequest 注解,和上面效果等价
    17. */
    18. @PostRequest("http://localhost:8080/hello")
    19. String simplePost();
    20. }

    除了GETPOST,也可以指定成其他几种 HTTP 请求方式(PUT, HEAD, OPTIONS, DELETE)。

    其中type属性的大小写不敏感,写成POSTpost效果相同。

    1. // GET请求
    2. @Request(
    3. url = "http://localhost:8080/hello",
    4. type = "get"
    5. )
    6. String simpleGet();
    7. // POST请求
    8. @Request(
    9. url = "http://localhost:8080/hello",
    10. type = "post"
    11. )
    12. String simplePost();
    13. // PUT请求
    14. @Request(
    15. url = "http://localhost:8080/hello",
    16. type = "put"
    17. )
    18. String simplePut();
    19. // HEAD请求
    20. @Request(
    21. url = "http://localhost:8080/hello",
    22. type = "head"
    23. )
    24. String simpleHead();
    25. // Options请求
    26. @Request(
    27. url = "http://localhost:8080/hello",
    28. type = "options"
    29. )
    30. String simpleOptions();
    31. // Delete请求
    32. @Request(
    33. url = "http://localhost:8080/hello",
    34. type = "delete"
    35. )
    36. String simpleDelete();

    另外,可以用@GetRequest, @PostRequest等注解代替@Request注解,这样就可以省去写type属性的麻烦了。

    1. // GET请求
    2. @Get("http://localhost:8080/hello")
    3. String simpleGet();
    4. // GET请求
    5. @GetRequest("http://localhost:8080/hello")
    6. String simpleGetRequest();
    7. // POST请求
    8. @Post("http://localhost:8080/hello")
    9. String simplePost();
    10. // POST请求
    11. @PostRequest("http://localhost:8080/hello")
    12. String simplePostRequest();
    13. // PUT请求
    14. @Put("http://localhost:8080/hello")
    15. String simplePut();
    16. // PUT请求
    17. @PutRequest("http://localhost:8080/hello")
    18. String simplePutRequest();
    19. // HEAD请求
    20. @HeadRequest("http://localhost:8080/hello")
    21. String simpleHead();
    22. // Options请求
    23. @Options("http://localhost:8080/hello")
    24. String simpleOptions();
    25. // Options请求
    26. @OptionsRequest("http://localhost:8080/hello")
    27. String simpleOptionsRequest();
    28. // Delete请求
    29. @Delete("http://localhost:8080/hello")
    30. String simpleDelete();
    31. // Delete请求
    32. @DeleteRequest("http://localhost:8080/hello")
    33. String simpleDeleteRequest();

    如上所示,请求类型是不是更一目了然了,代码也更短了。

    @Get@GetRequest两个注解的效果是等价的,@Post@PostRequest@Put@PutRequest等注解也是同理。

    :::caution 注意 HEAD请求类型没有对应的@Head注解,只有@HeadRequest注解。原因是容易和@Header注解混淆 :::