I need help regarding the Java Retrofit request:
Scenario 1: I have added an interceptor having few static headers.
Scenario 2: While requesting API, sending few dynamic headers also.
When the request completes, I check request headers like below.
response.raw().request().headers()
where I can see the static headers but not the dynamic headers.
below is the code for Interceptor to set static headers:
public class AuthInterceptor implements Interceptor {
public AuthInterceptor() {
}
protected String authtoken;
public AuthInterceptor(String authtoken) {
defaultHeader();
this.authtoken = authtoken;
}
public void setAuthtoken(String authtoken) {
this.authtoken = authtoken;
}
private Headers.Builder defaultHeader() {
final String xUserAgent = Util.SDK_NAME "/" Util.SDK_VERSION;
return new Headers.Builder()
.add("X-User-Agent", xUserAgent)
.add("User-Agent", Util.defaultUserAgent())
.add("Content-Type", "application/json");
}
public Headers.Builder addHeader(@NotNull String key, @NotNull String value) {
defaultHeader().add(key, value);
return defaultHeader();
}
@NotNull
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder request = chain.request().newBuilder()
.headers(defaultHeader().build());
if (this.authtoken != null) {
request.addHeader("authtoken", this.authtoken);
}
return chain.proceed(request.build());
}
}
And Sending dynamic headers like below.
@POST("stacks")
Call<ResponseBody> create(
@Header("organization_uid") String orgUid,
@Body RequestBody body);
CodePudding user response:
It looks to me like the problem is in your use of:
Request.Builder request = chain.request().newBuilder()
.headers(defaultHeader().build());
If you look at the documentation of the 'headers' method it states: Removes all headers on this builder and adds {@code headers}.
Just add each header with addHeader and you should be fine.