改装标头不会立即更改

时间:2019-03-03 23:57:25

标签: java android

在我的应用程序中,我有一个spinner,其中包含一些语言缩写示例(en,az和其他),我想将所选语言缩写设置为请求标头,因此我在每个请求中都需要使用该语言缩写将缩写保存在共享首选项中,并在我的ApiClient类中获取缩写, 每次更改微调框选择时,我都会更改共享首选项缩写值,但标头仅在我第一次选择语言时设置,而当我更改微调框选择时,标头不会更改

这是我的ApiClient类

private static final String BASE_URL = ApiUrls.server_url;

public static Retrofit getClient(Context context)
{

    SharedPrefUtil sharedPrefUtil = new SharedPrefUtil(context);
    String locale = sharedPrefUtil.getSelectedLanguage();

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    httpClient = httpClient.addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException
        {
            Request request = chain.request().newBuilder().header("Accept-Language",
                    locale).build();

            return chain.proceed(request);
        }
    });

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

    return retrofit;
}

这是我的ApiRequester类方法,用于将请求发送到服务器

public static void sendLogin(final Context context, Map<String, String> params,
                             final HttpResponses.onLoginSuccess onLoginSuccess) {

    DialogHelper.ProgressDialog progressDialog = showWaitDialog(context);

    if (hasInternetConnection(context)) {
        params.put("grant_type", "password");
        params.put("client_id", "raymon-client");
        params.put("client_secret", "raymon-secret");

        ApiInterface apiService = ApiClient.getClient(context).create(ApiInterface.class);
        Call<ResponseBody> call = apiService.loginRequest(params);

        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                progressDialog.dismiss();

                //result ok
                if (response.code() == 200)
                {
                    try
                    {
                        onLoginSuccess.loginResponse(JsonSuccessParser.parseLoginResponse
                                (context, response.body().string()));

                    } catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
                else if (response.code() == 403)
                {
                    onLoginSuccess.loginError(response.code());
                }
                else
                {
                    try
                    {
                        JsonErrorParser.parseServerError(context,response.errorBody().string());

                    } catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                progressDialog.dismiss();
                showNoConnectionDialog(context);
            }
        });
    } else {
        progressDialog.dismiss();
        showNoConnectionDialog(context);

    }


}

这是我的代码,用于在共享首选项中设置语言缩写

private void setUserLocale()
{
    String selected_country = countryCodeAdapter.getItem(country_code_spinner.
            getSelectedItemPosition()).language.abbreviation.toLowerCase();

    LocaleHelper.setLocale(this,selected_country);
}

当用户更改微调器位置时,如何立即更改标题?

1 个答案:

答案 0 :(得分:1)

ApiClient类中,您应该在locale方法内部初始化interceptor变量以反映您的更改。

示例)

private static final String BASE_URL = ApiUrls.server_url;

public static Retrofit getClient(Context context)
{
    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    httpClient = httpClient.addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException
        {
            SharedPrefUtil sharedPrefUtil = new SharedPrefUtil(context);
            String locale = sharedPrefUtil.getSelectedLanguage();
            Request request = chain.request().newBuilder().header("Accept-Language",
                    locale).build();

            return chain.proceed(request);
        }
    });

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

    return retrofit;
}

但是,如果值不断变化,则可能明确地将标头的值作为参数传递给服务,而不是拦截器。

示例)

public interface ApiService {
    Call<...> loginRequest(@Header("Accept-Language") String language, @QueryMap Map<String, String> params);
}

public static void sendLogin(final Context context, Map<String, String> params,
                             final HttpResponses.onLoginSuccess onLoginSuccess) {

    DialogHelper.ProgressDialog progressDialog = showWaitDialog(context);

    if (hasInternetConnection(context)) {
        params.put("grant_type", "password");
        params.put("client_id", "raymon-client");
        params.put("client_secret", "raymon-secret");

        SharedPrefUtil sharedPrefUtil = new SharedPrefUtil(context);
        String locale = sharedPrefUtil.getSelectedLanguage();

        ApiInterface apiService = ApiClient.getClient(context).create(ApiInterface.class);
        Call<ResponseBody> call = apiService.loginRequest(locale, params);

        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                progressDialog.dismiss();

                //result ok
                if (response.code() == 200)
                {
                    try
                    {
                        onLoginSuccess.loginResponse(JsonSuccessParser.parseLoginResponse
                                (context, response.body().string()));

                    } catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
                else if (response.code() == 403)
                {
                    onLoginSuccess.loginError(response.code());
                }
                else
                {
                    try
                    {
                        JsonErrorParser.parseServerError(context,response.errorBody().string());

                    } catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                progressDialog.dismiss();
                showNoConnectionDialog(context);
            }
        });
    } else {
        progressDialog.dismiss();
        showNoConnectionDialog(context);

    }
}