问题
I have a Problem with replace the placeholder in the url with the auth-token.
My OkHttpClient:
OkHttpClient clientToken = new OkHttpClient.Builder()
.addInterceptor(tokenInterceptor)
.addInterceptor(interceptor)
.connectTimeout(100, TimeUnit.SECONDS)
.readTimeout(100, TimeUnit.SECONDS)
.build();
My TockenInspector:
private class TokenInterceptor implements Interceptor{
@Override
public Response intercept(Chain chain) throws IOException {
Response mainResponse = chain.proceed(chain.request());
//Auth Data available?
if(RestClient.this.isAuthenticationDataSet()){
//Get Token
String currentToken = getToken(RestClient.this.authCustomerNumber,
RestClient.this.authUser,
RestClient.this.authPassword,
RestClient.this.authDeviceId);
//Original RequestData
Request originalRequest = chain.request();
HttpUrl originalUrl = originalRequest.url();
List<String> urlSegments = originalUrl.pathSegments();
//New URL
boolean tokenFoundInSegments = false;
HttpUrl.Builder newUrlBuilder = originalUrl.newBuilder();
//Search token placeholders in url segments
for(int i=0; i<urlSegments.size(); i++){
String segment = urlSegments.get(i);
if(segment.equals(tokenPlaceholder)){
segment = currentToken;
tokenFoundInSegments = true;
}
newUrlBuilder.setPathSegment(i, segment);
}
//If not found in segments: Set token as get param
if(!tokenFoundInSegments){
newUrlBuilder.addQueryParameter("token", currentToken);
}
HttpUrl url = newUrlBuilder.build();
Request tokenRequest = originalRequest.newBuilder().url(url).build();
return chain.proceed(tokenRequest);
}else{
//No auth data available
return chain.proceed(chain.request());
}
}
}
My Call:
ObservableField<UserLoginData> userdata =
UserBackend.getInstance(context).getUserLoginData();
//order the basket
Call<RestResult<BasketResult>> call =
this.restAPIBasket.orderBasket(basket.getId(), userdata.get().getPassword());
call.enqueue(new Callback<RestResult<BasketResult>>() {
.....
URL: URL/R_token/password?format=json
My Problem:
when I debug, retrofit executes a call without setting the token and then does it go through the tokenInterceptor class and make the call again. Can anyone help me to fix this Problem? I can not always use the token as a query but in certain URLs only as a path
回答1:
The problem was: Response mainResponse = chain.proceed(chain.request());
chain.proceed()
make the call witheout set the token and the return with set the token. also calls twice. I removed the first and it's work correct
来源:https://stackoverflow.com/questions/51209066/retrofit2-put-token-in-url-with-placeholder