gpt4 book ai didi

java - 如何调用android中实现Authenticator的类

转载 作者:行者123 更新时间:2023-12-02 09:05:41 25 4
gpt4 key购买 nike

我创建了一个从 Authenticator 类扩展的子类。我在此 Authenticator 类中从 AsyncTask 调用 doInBackground 方法。代码如下

TokenAuthenticator.java

public class TokenAuthenticator implements Authenticator {
@Override
public Request authenticate(Route route, Response response) throws IOException {
try {
Log.i("TokenAuth", "Testing");
new AWSInitiator(AppSetting.getInstance().getApplicationContext()).execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}

return response.request().newBuilder().header("Authorization", "Bearer " + AppSetting.getInstance().getSDKDataManager().getAccessToken()).build();
}
}

未调用此类(Log 未打印)。这里AWSInitiator是一个扩展AsyncTask

的类

最佳答案

我正在使用下面的类,其中包含 validator 和拦截器。如果您只需要 validator 代码,可以删除拦截器代码。

注意:-我在下面的代码中将改造与 GSON 一起使用

    class SupportInterceptor(context: Context) : Interceptor, Authenticator {
var ctx: Context = context
var prefManager: PrefManager

init {
prefManager = PrefManager.getInstance(ctx)
}

/**
* Interceptor class for setting of the headers for every request
*/
override fun intercept(chain: Interceptor.Chain): Response {

var request = chain.request()
request =
request.newBuilder().addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.addHeader(
"Authorization",
"Bearer " + prefManager.getString(PreferenceConstants.ACCESS_TOKEN)
)
.build()
return chain.proceed(request)

}

/**
* Authenticator for when the authToken need to be refresh and updated
* everytime we get a 401 error code
*/
@Throws(IOException::class)
override fun authenticate(route: Route?, response: Response): Request? {
if (response.code == 401) {
val client = OkHttpClient()
val jsonObject = JSONObject()
val dataObject = JSONObject()
dataObject.accumulate("userCode", prefManager.getString(PreferenceConstants.USER_ID))
dataObject.accumulate("password", prefManager.getString(PreferenceConstants.PASSWORD))
jsonObject.accumulate("Data", dataObject)
val json = "application/json; charset=utf-8".toMediaTypeOrNull()
val body = RequestBody.create(json, jsonObject.toString())
val request = Request.Builder()
.url(APIClient.COMPLETE_URL + "API ENDPOINTS")
.post(body)
.build()
val res = client.newCall(request).execute()
if (res.isSuccessful) {
try {
val jsonObj = JSONObject(res.body?.string())
val accessToken = jsonObj.opt("accessToken")
val statusCode = jsonObj.opt("statusCode")
if (statusCode.toString().equals("-1") || accessToken == null || accessToken.toString().equals(
"null"
)
) {
userLogout()
return null
} else {
prefManager.putString(
PreferenceConstants.ACCESS_TOKEN,
accessToken as String
)
return response.request.newBuilder()
.header("Authorization", "Bearer " + accessToken as String)
.build();
}
} catch (e: Exception) {
return null
}
} else {
return null
}
}
return null
}

fun userLogout() {
prefManager?.putBoolean(PreferenceConstants.IS_LOGGED_IN, false)
val intent = Intent(ctx!!, LoginActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
ctx.startActivity(intent)
///ctx?.finishAffinity()
}
}

这就是将其添加到 http 客户端的方式

httpClient.authenticator(supportInterceptor)

关于java - 如何调用android中实现Authenticator的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59834739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com