Я не могу добавить заголовок "токен доступа": "aldsjfakl-- токен длинного доступа == alkfa" в моем заголовке. Я хочу сделать это всякий раз, когда мой токен истек. Я пытаюсь сделать это с помощью класса аутентификатора http3. и создание одноэлементного класса модифицированного экземпляра.
Итак, класс Authenticator выглядит примерно так ..
public class TokenAuthenticator implements Authenticator {
public static final String TAG = TokenAuthenticator.class.getSimpleName();
@Override
public Request authenticate(Route route, Response response) throws IOException {
RequestBody requestBody = new MultipartBody.Builder()
.addFormDataPart("phone", "0000003000").build();
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(BASE_URL + "api/user/profile/login")
.post(requestBody)
.build();
Response response1 = client.newCall(request).execute();
Gson gson = new Gson();
RegisterResponse registerResponse = gson.fromJson(response1.body().toString(), RegisterResponse.class);
String newAccessToken = registerResponse.getResult().getToken();
Log.d(TAG, "Token Auth is authenticating");
return response.request().newBuilder()
.header("access-token", newAccessToken)
.build();
}
}
Мой Singleton ApiClient здесь.
public class ApiClient {
private static Retrofit retrofit = null;
private ApiClient() {
if (retrofit != null) {
throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
}
}
public static final String BASE_URL = "http://10.0.2.2:3000/";
public static synchronized Retrofit getClient() {
if (retrofit == null) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.level(HttpLoggingInterceptor.Level.BODY);
TokenAuthenticator tokenAuthenticator = new TokenAuthenticator();
OkHttpClient client = new OkHttpClient.Builder().authenticator(tokenAuthenticator).addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit;
}
return retrofit;
}
}
и я звоню из mainactivity. java эта функция для инициализации и запроса на конкретный URL. он всегда возвращает
void makeMockApi() throws IOException {
UserDetails userDetails = new UserDetails();
userDetails.setPhoneNumber("0000003000");
BranchRequest branchRequest= new BranchRequest();
branchRequest.setCityId("5e08d7387c263432e67d4ac0");
branchRequest.setPhone("0000003000");
branchRequest.setLatitude(13.0825);
branchRequest.setLongitute(82.2935);
ApiClient.getClient().create(MyService.class).getBranchList(branchRequest).enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
это мои журналы ..
--> POST http://10.0.2.2:3000/api/user/branch/getBranchList
2020-01-13 16:35:15.957 12907-13002/com.example.myapplication D/OkHttp: Content-Type: application/json; charset=UTF-8
2020-01-13 16:35:15.958 12907-13002/com.example.myapplication D/OkHttp: Content-Length: 97
2020-01-13 16:35:15.959 12907-13002/com.example.myapplication D/OkHttp: {"cityId":"5e08d7387c263432e67d4ac0","latitude":13.0825,"longitute":82.2935,"phone":"0000003000"}
2020-01-13 16:35:15.959 12907-13002/com.example.myapplication D/OkHttp: --> END POST (97-byte body)
2020-01-13 16:35:16.063 12907-13002/com.example.myapplication D/OkHttp: <-- 403 Forbidden http://10.0.2.2:3000/api/user/branch/getBranchList (103ms)
2020-01-13 16:35:16.064 12907-13002/com.example.myapplication D/OkHttp: X-Powered-By: Express
2020-01-13 16:35:16.064 12907-13002/com.example.myapplication D/OkHttp: Vary: X-HTTP-Method-Override
2020-01-13 16:35:16.065 12907-13002/com.example.myapplication D/OkHttp: Access-Control-Allow-Origin: *
2020-01-13 16:35:16.065 12907-13002/com.example.myapplication D/OkHttp: Content-Type: application/json; charset=utf-8
2020-01-13 16:35:16.065 12907-13002/com.example.myapplication D/OkHttp: Content-Length: 47
2020-01-13 16:35:16.065 12907-13002/com.example.myapplication D/OkHttp: ETag: W/"2f-3MuuSAVLMAUNt206QxWk5J3r4fw"
2020-01-13 16:35:16.065 12907-13002/com.example.myapplication D/OkHttp: Date: Mon, 13 Jan 2020 11:05:16 GMT
2020-01-13 16:35:16.065 12907-13002/com.example.myapplication D/OkHttp: Connection: keep-alive
2020-01-13 16:35:16.068 12907-13002/com.example.myapplication D/OkHttp: {"auth":false,"message":"Unauthorized request"}
2020-01-13 16:35:16.068 12907-13002/com.example.myapplication D/OkHttp: <-- END HTTP (47-byte body)
Нет проблем с моим классом обслуживания. Спасибо.