要設置根URL您可以使用此方法,以恆定
@Rest(rootUrl = "http://company.com/ajax/services", converters = { MappingJackson2HttpMessageConverter.class }, interceptors = MyAuthInterceptor.class)
public interface MyRestClient {
@Get("/events")
EventList getEvents();
}
請注意,我們在@Rest標註的參數設置了一個攔截替換字符串。 因此,創建這樣一個類:
@EBean(scope = Scope.Singleton)
public class MyAuthInterceptor implements ClientHttpRequestInterceptor {
@Bean
MyAuthStore authStore;
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
HttpHeaders headers = request.getHeaders();
HttpAuthentication auth = new HttpBasicAuthentication(authStore.getUsername(), authStore.getPassword());
headers.setAuthorization(auth);
return execution.execute(request, body);
}
}
現在正在執行的請求MyAuthInterceptor.intercept()之前被調用,並根據自己的喜好
在你的主要的build.gradle文件,你可以添加你可以設置你的認證數據Android的元素中
productFlavors {
development {
buildConfigField "String", "SERVICE_URL_BASE", "\"dev.xxx.com/rest\""
}
test {
buildConfigField "String", "SERVICE_URL_BASE", "\"test.xxx.com/rest\""
}
production {
buildConfigField "String", "SERVICE_URL_BASE", "\"production.xxx.com/rest\""
}
}
然後在你的@Rest註釋您可以使用此代碼來獲取當前的味道值:
@Rest(rootUrl = "https://" + BuildConfig.SERVICE_URL_BASE)
現在您可以選擇要使用的構建變體(variant = flavor + buildType)以使用期望的值。要選擇變體,您可以使用相應的視圖,它應該出現在android studio的左側。
這個技術是很有用的,以避免產生香味的包樹只使用不同variabiles
謝謝回答,我怎麼會在'@ Rest'使用'R.string.whiteLabelApiBaseHost'?我可以在攔截器中設置rootUrl嗎? – simo
我不認爲你可以在攔截器內設置rootUrl,當然不容易。你爲什麼需要這個?可能你可以用另一種方式解決。爲什麼你需要從字符串資源獲取rootUrl?如果你需要使用基於環境的不同url,我建議使用gradle構建變量 – firegloves
你能寫一個使用gradle build變量的例子來根據環境在'@ Rest'上設置RootUrl嗎? – simo