Retrofit 中的 POST 请求发送空正文

问题描述 投票:0回答:7

我的 api 在发出 post 请求时需要一个空的 json 正文 (

{ }
)。我如何在 Retrofit 和 Jackson 中进行设置?

我尝试传递

null
、空字符串和
"{}"
,但无法使其正常工作。

@POST(my/url)
Call<MyResponse> createPostRequest(@Body Object empty);

如何设置空的 JSON 正文?

java request jackson retrofit
7个回答
11
投票

一个空对象可以为 Kotlin 完成此操作:

interface ApiService {
    @POST("your.url")
    fun createPostRequest(@Body body: Any = Object()): Call<YourResponseType>
}

6
投票

试试这个。它现在对我有用。

@POST(my/url)
Call<MyResponse> createPostRequest(@Body Hashmap );

使用此方法时,将

new HasMap
作为参数

apiservice.createPostRequest(new HashMap())

4
投票

空类就可以了:

class EmptyRequest {
    public static final EmptyRequest INSTANCE = new EmptyRequest();
}

interface My Service {

    @POST("my/url")
    Call<MyResponse> createPostRequest(@Body EmptyRequest request);

}

myService.createPostRequest(EmptyRequest.INSTANCE);

3
投票

老问题,但我通过使用

okhttp3.Interceptor
找到了更合适的解决方案,如果不存在主体,则添加一个空主体。此解决方案不需要您为空的
@Body
添加额外的参数。

示例:

Interceptor interceptor = chain -> {
    Request         oldRequest = chain.request();
    Request.Builder newRequest = chain.request().newBuilder();

    if ("POST".equals(oldRequest.method()) && (oldRequest.body() == null || oldRequest.body().contentLength() <= 0)) {
        newRequest.post(RequestBody.create(MediaType.parse("application/json"), "{}"));
    }

    return chain.proceed(newRequest.build());
};

然后您可以像这样创建服务实例:

OkHttpClient.Builder client = new OkHttpClient.Builder();
client.addInterceptor(interceptor);

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("YourURL")
        .client(client.build())
        .build();

MyService service = retrofit.create(MyService.class);

2
投票

用途:

@POST("something")
Call<MyResponse> createPostRequest(@Body Object o);

然后致电:

createPostRequest(new Object())

0
投票

这是 Kotlin 中的答案:

    @POST("CountriesList")
fun getCountriesNew(@Body body: HashMap<String, String>) : Call<CountryModel>

      val call = RetrofitClient.apiInterface.getCountriesNew(HashMap())

0
投票

“{}”.toRequestBody()

© www.soinside.com 2019 - 2024. All rights reserved.