How to perform a DELETE request without return typ

2019-04-05 09:20发布

问题:

I need perform a DELETE request using Retrofit. So, my code snippet of the interface looks like this:

@DELETE("/api/item/{id}")
void deleteItem(@Path("id") int itemId);

But I get the error:

java.lang.IllegalArgumentException: ApiItem.deleteItem: Must have either a return type or Callback as last argument.

However, according to the rules of Rest API, I shouldn't receive any response to DELETE request. How should I specify it in the interface?

Thanks.

回答1:

You have to add Callback as last argument in request method if you want to have void method. You can useCallback<Response>.

You have to change this:

@DELETE("/api/item/{id}")
void deleteItem(@Path("id") int itemId);

to :

@DELETE("/api/item/{id}")
void deleteItem(@Path("id") int itemId, Callback<Response> callback);

Or you can return just Response

@DELETE("/api/item/{id}")
Response deleteItem(@Path("id") int itemId);


回答2:

In Retrofit 2.0, You can use Call interface for the result of your request as below.

@DELETE("/api/item/{id}")
Call<Response> deleteItem(@Path("id") int itemId);

...

Call<Response> call = YourServiceInstance.deleteItem(10);
call.enqueue(new Callback<Response>() {
...
});


回答3:

@FormUrlEncoded
@HTTP(method = "DELETE", path = "manage-feed", hasBody = true)
Call<ResponseBody> deletePost(@Field("post_id") Integer postId, @Field("share_id") Integer sharedMapId);