【问题标题】:Retrofit 2 add support for custom / other request methods (HTTP verbs)Retrofit 2 添加对自定义/其他请求方法(HTTP 动词)的支持
【发布时间】:2017-02-15 09:34:00
【问题描述】:

在 Retrofit 2 中,我可以在服务中使用注释来定义需要使用的 HTTP 方法。例如:

public interface UserService {

    @GET("users")
    Call<UsersResponse> getAllUsers(@Header("access-token") String token)

    @POST("user")
    Call<UserResponse> postUser(@Header("access-token") String token, @Body User user)

}

我觉得这很方便,但是我缺少一些 HTTP 请求方法(动词),例如 LINK 和 UNLINK。是否有可能以某种方式扩展 Retrofit 以创建对额外方法的支持?

【问题讨论】:

    标签: android rest httprequest retrofit retrofit2


    【解决方案1】:

    可以使用 HTTP 注释:

    public interface AccountService {
    
        @HTTP(method = "LINK", path = "users",  hasBody = true)
        Call<BaseResponse> linkUsers(@Header("access-token") String token, @Body LinkUsersRequest linkUsersRequest);
    
    }
    

    您还可以使用 HTTP 注释创建带有请求正文的 DELETE 请求

    【讨论】:

    • 你好 Bart,我的代码不工作它总是说自定义方法 AUTH,不能有正文 @Headers("Content-Type: application/json") @HTTP(method = "AUTH", path = "login/{deviceId}", hasBody = true) Call getLogin(@Path("deviceId") int deviceId, @Body RequestBody 密码);我正在使用改造 2.X
    猜你喜欢
    • 1970-01-01
    • 2016-11-18
    • 2018-07-10
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    • 2013-03-19
    相关资源
    最近更新 更多