我如何从java类传递令牌来改进APIClient

时间:2017-09-25 09:19:16

标签: android json parsing retrofit retrofit2

  

我正在使用改造库来解析来自json的数据。但现在我需要在我的请求中传递令牌。我在一个Global类中设置了令牌。现在我想在APIClient.But中使用该令牌,当我通过时,它通过null。

这是我的APIClient

public class APIClient  {
    public static final String BASE_URL = "http://kartpays.bizs/api/v5/";
    private static Retrofit retrofit = null;
    public static final String FOLLOW_URL ="http://kartpays.biz/api/v1/follow/";

    public static Retrofit getRetrofitInstance() {

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request originalRequest = chain.request();


                Request request = originalRequest.newBuilder()
                        .header("token", **I want to pass token here**)
                        .header("Content-Type", "application/json")
                        .method(originalRequest.method(), originalRequest.body())
                        .build();

                return chain.proceed(request);
            }
        });
        OkHttpClient client = httpClient.build();

        retrofit = new Retrofit.Builder()
                .baseUrl(FOLLOW_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

        return retrofit;
    }
}

在此课程中我存储了令牌

 public class LibFile {
    Context context;

    public  static SharedPreferences settings;
    private static LibFile instance;
    public static LibFile getInstance(Context context) {
        if (instance == null) {
            instance = new LibFile(context);
        }
        return instance;
    }

    public LibFile(Context context) {
        this.context = context;
        settings = context.getSharedPreferences(AppConstants.PREFS_FILE_NAME_PARAM, 0);
    }

    public String getUser_id() {
        return settings.getString("user_id", "");
    }

    public void setUser_id(String link) {
        settings.edit().putString("user_id", link).commit(); //get link from here
    }

    public String getToken() {
        return settings.getString("token","");//pass key here
    }

    public static void setToken(String userName) {
        settings.edit().putString("token", userName).commit();//get key from here
    }

    public void clearCache() {
        settings.edit().clear().commit();
        settings.edit().remove("link").commit();
    }
}
  

请建议我如何动态传递令牌。我无法传递静态令牌,因为它会不断变化。谢谢提前

3 个答案:

答案 0 :(得分:0)

如果您的令牌存储在SharedPreference中,请查看以下代码更改

  public static Retrofit getRetrofitInstance(Context mContext) {

        SharedPreferences settings = mContext.getSharedPreferences(AppConstants.PREFS_FILE_NAME_PARAM, 0);

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request originalRequest = chain.request();


                Request request = originalRequest.newBuilder()
                        .header("token", settings.getString("token", ""))
                        .header("Content-Type", "application/json")
                        .method(originalRequest.method(), originalRequest.body())
                        .build();

                return chain.proceed(request);
            }
        });
        OkHttpClient client = httpClient.build();

        retrofit = new Retrofit.Builder()
                .baseUrl(FOLLOW_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

        return retrofit;
    }
}

答案 1 :(得分:0)

适合您代码的更好解决方案是:

 Request request = originalRequest.newBuilder()
                        .header("token", LibFile.getInstance(mContext).getToken())
                        .header("Content-Type", "application/json")
                        .method(originalRequest.method(), originalRequest.body())
                        .build();

选中以下行:.header("token", LibFile.getInstance(mContext).getToken())

从LibFile中获取一个实例并获取一个令牌。

答案 2 :(得分:0)

在您的http请求中,标题键应为“授权”而不是“令牌”。

Request request = originalRequest.newBuilder()
                    .header("Authorization", **I want to pass token here**)
                    .header("Content-Type", "application/json")
                    .method(originalRequest.method(), originalRequest.body())
                    .build();

您可以使用以下方法从共享偏好设置中获取和获取令牌。

public static boolean setStringPreference(String key, String value) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    if (preferences != null && !TextUtils.isEmpty(key)) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(key, value);
        return editor.commit();
    }
    return false;
}

public static String getStringPreference(String key) {
    String value = null;
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    if (preferences != null) {
        value = preferences.getString(key, null);
    }
    return value;
}