我的 api 在发出 post 请求时需要一个空的 json 正文 (
{ }
)。我如何在 Retrofit 和 Jackson 中进行设置?
我尝试传递
null
、空字符串和 "{}"
,但无法使其正常工作。
@POST(my/url)
Call<MyResponse> createPostRequest(@Body Object empty);
如何设置空的 JSON 正文?
一个空对象可以为 Kotlin 完成此操作:
interface ApiService {
@POST("your.url")
fun createPostRequest(@Body body: Any = Object()): Call<YourResponseType>
}
试试这个。它现在对我有用。
@POST(my/url)
Call<MyResponse> createPostRequest(@Body Hashmap );
使用此方法时,将
new HasMap
作为参数
apiservice.createPostRequest(new HashMap())
空类就可以了:
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);
老问题,但我通过使用
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);
用途:
@POST("something")
Call<MyResponse> createPostRequest(@Body Object o);
然后致电:
createPostRequest(new Object())
这是 Kotlin 中的答案:
@POST("CountriesList")
fun getCountriesNew(@Body body: HashMap<String, String>) : Call<CountryModel>
val call = RetrofitClient.apiInterface.getCountriesNew(HashMap())
“{}”.toRequestBody()