[英]Send empty body in POST request in Retrofit
我的 api 在发出 post 请求时需要一个空的 json body (
{ }<\/code> )。
如何在 Retrofit 和 Jackson 中进行设置?
我尝试传递
null<\/code> 、空字符串和
"{}"<\/code>但无法使其正常工作。
@POST(my/url)
Call<MyResponse> createPostRequest(@Body Object empty);
试试这个。 它现在对我有用。
@POST(my/url)
Call<MyResponse> createPostRequest(@Body Hashmap );
使用此方法时,将new HasMap
作为参数传递
apiservice.createPostRequest(new HashMap())
一个空对象为Kotlin做这件事:
interface ApiService {
@POST("your.url")
fun createPostRequest(@Body body: Any = Object()): Call<YourResponseType>
}
空类可以解决问题:
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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.