リクエスト毎にリクエストヘッダの値を変更する必要があったので作ってみた。
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