Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit 2: Default Accept-Language

Is there any way to automatically add Accept-Language header based on OS settings?

For example: I have English (US) as my system lang, it would be great to have Accept-Language: en-us added in some simple way...

Also Android N allows to select multiple locales in settings, so it would be great to use this like: Accept-Language: da, en-gb;q=0.8, en;q=0.7

Thanks.

like image 283
oleynikd Avatar asked Jun 13 '16 13:06

oleynikd


1 Answers

In case someone is looking for a solution how to provide a list of preferred languages as accept-language, in Android here is how to do that. Note: Setting a list of preferred languages is only available since API Level 24

  public class AcceptLanguageHeaderInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
      Request originalRequest = chain.request();
      Request requestWithHeaders = originalRequest.newBuilder()
        .header("Accept-Language", getLanguage())
        .build();
      return chain.proceed(requestWithHeaders);
    }

    private String getLanguage() {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        return LocaleList.getDefault().toLanguageTags();
      } else {
        return Locale.getDefault().getLanguage();
      }
    }
  }
like image 140
user2350644 Avatar answered Sep 22 '22 22:09

user2350644