如何在改造中发送带有正文的HTTP删除?

Hop*_*ful 20 android retrofit

当我尝试创建一个删除方法时:

public interface ImageService {
    @DELETE("api/v1/attachment")
    Call<BaseResponse> delete(@Body DeleteModel deleteModel);
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误基本上归结为来自stacktrace的这些行:

E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Failure delivering result
java.lang.IllegalArgumentException: Non-body HTTP method cannot contain @Body.
Caused by: java.lang.IllegalArgumentException: Non-body HTTP method cannot contain @Body.
Run Code Online (Sandbox Code Playgroud)

如何在删除方法中添加正文?

我在这里搜索但发现3没有答案,没有使用改造.

Mar*_*il4 53

一个更简化的答案.

@FormUrlEncoded
@HTTP(method = "DELETE", path = "/api/analysis_delete", hasBody = true)
Call<Analysis_Delete_RequestResult_Api10> analysis_delete_api10(@Field("seq") String seq);
Run Code Online (Sandbox Code Playgroud)

这样就可以了.

  • 如果您需要发送@ Body,则需要删除@ FormUrlEncoded. (9认同)

Sha*_*aur 10

这是我的版本

@HTTP(method = "DELETE", path = "{login}", hasBody = true)
Call<ResponseBody> getData(@Path("login") String postfix, @Body Map<String, Object> options);
Run Code Online (Sandbox Code Playgroud)


hea*_*svk 9

这是文档的摘录,它是 HTTP 注释的记录功能。

This annotation can also used for sending DELETE with a request body:

 interface Service {
   @HTTP(method = "DELETE", path = "remove/", hasBody = true)
   Call<ResponseBody> deleteObject(@Body RequestBody object);
 }
Run Code Online (Sandbox Code Playgroud)

https://square.github.io/retrofit/2.x/retrofit/retrofit2/http/HTTP.html


Yft*_*ach 6

如果您使用的是不支持@HTTP 的旧版本,您还可以添加另一个实现@RestMethod 的接口

import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import retrofit.http.RestMethod;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/** Make a DELETE request to a REST path relative to base URL with body. */
@Target(METHOD)
@Retention(RUNTIME)
@RestMethod(value = "DELETE", hasBody = true)
public @interface DELETEWITHBODY {
  String value();
}
Run Code Online (Sandbox Code Playgroud)

然后用法变成:

public interface ImageService {
    @DELETEWITHBODY("api/v1/attachment")
    Call<BaseResponse> delete(@Body DeleteModel deleteModel);
}
Run Code Online (Sandbox Code Playgroud)