我正在使用Square的Retrofit库进行短期网络通话。我在每个请求中都包含一些数据作为@Query
参数。像这样:
@GET("/thingOne.php")
void thingOne(
@Query("app_version") String appVersion,
@Query("device_type") String deviceType,
Callback<Map<String,Object>> callback
);
@GET("/thingTwo.php")
void thingTwo(
@Query("app_version") String appVersion,
@Query("device_type") String deviceType,
Callback<Map<String,Object>> callback
);
必须为appVersion
中列出的每个端点定义deviceType
和Interface
,这很麻烦。有没有办法设置每个请求应包含的基本参数集?类似于我们设置公共Authorization Header
的方式?
RestAdapter restAdapter = new RestAdapter.Builder()
.setServer("...")
.setRequestHeaders(new RequestHeaders() {
@Override
public List<Header> get() {
List<Header> headers = new ArrayList<Header>();
Header authHeader = new Header(
"Authorization", "Bearer " + token);
headers.add(authHeader);
}
return headers;
}
})
.build();
this.service = restAdapter.create(ClientInterface.class);
答案 0 :(得分:55)
您可以通过向RestAdapter添加自定义RequestInterceptor来确保所有请求都具有这些查询参数
RequestInterceptor requestInterceptor = new RequestInterceptor()
{
@Override
public void intercept(RequestFacade request) {
request.addQueryParam("app_version", "Version 1.x");
request.addQueryParam("device_type", "Samsung S4");
}
};
restAdapter.setRequestInterceptor(requestInterceptor)