2016-09-13 9 views
1

동적으로 헤더 및 본문을 웹 API에 전달하려고합니다. 그래서, 다음과 같이 구현 :retrofit 2 : 본문과 함께 동적 헤더 전달

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()가 null) 받고 있지 않다.

누구나 동적 머리글과 본문을 함께 전달하는 방법을 제안 할 수 있습니까?

참고 :this 튜토리얼을 밟았지만 두 가지 방법 모두를 통과하지 못했습니다.

+0

이 anwser http://stackoverflow.com/questions/29884967/how-to-dynamically-set-headers-in-retrofit을 확인하십시오 :

그냥 같은 뭔가 조건이있는 경우에 선 아래 포장 -android/29885004 # 29885004 –

+0

@RobertEstivill 답변에 표시된 것처럼 이미 헤더를 동적으로 전달하고 있습니다. –

답변

0

내가 알 수있는 한, 머리글과 본문을 동시에 전달할 수있는 방법은 없습니다.

그러나 당신은 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(isUserLoggedIn()) 
    ongoing.addHeader("Authorization", getToken(app));