问题描述
我在用 auth-token 替换 url 中的占位符时遇到问题.
I have a Problem with replace the placeholder in the url with the auth-token.
我的 OkHttpClient:
My OkHttpClient:
OkHttpClient clientToken = new OkHttpClient.Builder()
.addInterceptor(tokenInterceptor)
.addInterceptor(interceptor)
.connectTimeout(100, TimeUnit.SECONDS)
.readTimeout(100, TimeUnit.SECONDS)
.build();
我的令牌检查员:
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());
}
}
}
我的电话:
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/R_token/password?format=json
URL: URL/R_token/password?format=json
我的问题:
当我调试时,改造会在不设置令牌的情况下执行调用,然后它会通过 tokenInterceptor 类并再次进行调用.谁能帮我解决这个问题?我不能总是将令牌用作查询,而只能在某些 URL 中用作路径
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
推荐答案
问题是:Response mainResponse = chain.proceed(chain.request());
chain.proceed()
调用时不设置令牌,返回时设置令牌.也叫了两次.我删除了第一个,它的工作正常
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
这篇关于Retrofit2 将令牌放入带有占位符的 URL 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!