LoginSignup
2
2

More than 5 years have passed since last update.

Retrofit 2でリクエスト毎にリクエストヘッダの値を変更する

Last updated at Posted at 2016-01-15

リクエスト毎にリクエストヘッダの値を変更する必要があったので作ってみた。

Volleyからの載せ替えなのでVolleyちっくで一般的かはわかりませんが。

RestClient.java
public class RestClient {
    private static Retrofit sClient;
    private static HashMap<String, String> sHeaders;

    public static void build(String baseUrl) {
        OkHttpClient okClient = new OkHttpClient();
        okClient.interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();

                Request.Builder builder = request.newBuilder();
                for(HashMap.Entry<String, String> entry : sHeaders.entrySet()){
                    builder.addHeader(entry.getKey(), entry.getValue());
                }

                return chain.proceed(builder.build());
            }
        });

        sClient = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(okClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public static Retrofit getInstance() {
        return getInstance(new HashMap<String, String>());
    }

    public static Retrofit getInstance(HashMap<String, String> headers) {
        sHeaders = headers;
        return sClient;
    }
}

使うときはこんな感じ

// ここは一度だけ
RestClient.build("http://api.example.com/");

// ここから下はリクエスト毎に
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Hoge", "hogehoge");
headers.put("User-Agent", "Mozilla");

GitHubService service = RestClient.getInstance(headers).create(GitHubService.class);

サーバ側

HTTP_HOGE:hogehoge
HTTP_USER_AGENT:Mozilla

※勘違いしている部分があったため、再度書き直しました。

参考

http://square.github.io/retrofit/
http://stackoverflow.com/questions/32605711/adding-header-to-all-request-with-retrofit-2

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2