我想将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();
}
});
但是这样,我没有得到空响应(response.body()
为空)。
有人可以建议如何将动态标题和正文传递到一起吗?
注意:我浏览了this教程,但没有找到通过这两种方法的方法。
答案 0 :(得分:0)
据我所知,没有办法同时传递Header和Body。
但您可以将 Employee ID |Job| Function| Level|Date of change
1 | x | a | A1 | 01/05/2014
1 | y | a | A1 | 02/04/2015
1 | y | a | A2 | 25/08/2015
1 | z | a | A3 | 27/12/2015
1 | z | c | A3 | 01/03/2016
2 | t | b | B1 | 12/05/2013
2 | v | b | B1 | 13/04/2014
2 | w | b | B3 | 12/01/2016
添加到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());
}
});
答案 1 :(得分:0)
您正在使用 Retrofit2。完全可以使用动态标头,例如:
@POST("hello-world")
fun getKaboom(
@Body body: TheBody,
@Header("hello-world-header") helloWorldHeader: String? = "kaboom"
): Single<KaboomResponse>