我想动态传递Header和Body给Web Api。因此,我实现如下:
public interface NotificationService {
@POST("user/update/notification")
Call<JsonObject> notification(@Header("Authorization") String authorization, @Body NotificationRequest notificationRequest);
}
使用这个作为,
showProgressDialog();
NotificationRequest notificationRequest = new NotificationRequest(checked ? ApiConstants.IS_ON : ApiConstants.IS_OFF, getUserId());
NotificationService notificationService = ApiFactory.provideNotificationService();
Call<JsonObject> call = notificationService.notification(getAuthorizationHeader(), notificationRequest);
call.enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
logDebug(SettingsFragment.class, response.body().toString());
hideProgressDialog();
}
@Override
public void onFailure(Call<JsonObject> call, Throwable t) {
hideProgressDialog();
}
});
但是这样,我没有得到null响应(response.body()
是null)。
谁能建议如何传递动态头和体在一起?
注意:我看了这个教程,但没有找到同时通过的方法
据我所知,没有办法同时传递Header和Body。
但是你可以将Interceptor
加入OkHttpClient
,如下所示:
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.cache(cache);
builder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder ongoing = chain.request().newBuilder();
ongoing.addHeader("Authorization", getToken(app));
return chain.proceed(ongoing.build());
}
});
这将在每个请求中添加授权头。您可以控制在某些条件下添加头,例如如果用户已登录,则只应添加请求头。
只要在if条件下换行,像这样:
if(isUserLoggedIn())
ongoing.addHeader("Authorization", getToken(app));
您正在使用Retrofit2。使用动态头是完全可能的,例如:
@POST("hello-world")
fun getKaboom(
@Body body: TheBody,
@Header("hello-world-header") helloWorldHeader: String? = "kaboom"
): Single<KaboomResponse>