【发布时间】:2017-08-30 20:58:35
【问题描述】:
我正在尝试学习 Retrofit 并在我现在的项目中使用它。我已经成功实现了一些基本的 GET 和 POST 方法,但是现在我一直在尝试向请求的标头中添加信息。
这是客户端类:
public class CategoryClient {
public static final String BASE_URL = "URL is here";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
这是带有GET方法的接口:
public interface CategoryService {
@GET("/v3/projects/{projectId}/categories/")
Call<CategoryResponse> getProjectCategories(@Query("projectId") String projectId);
}
这是我的类别类:
public class Category2 {
@SerializedName("_id")
private String _id;
@SerializedName("name")
private String name;
@SerializedName("tasks")
private int tasks;
public Category2(String _id, String name, int tasks) {
this._id = _id;
this.name = name;
this.tasks = tasks;
}
public String get_id(){
return _id;
}
public void set_id(String _id){
this._id = _id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getTasks() {
return tasks;
}
public void setTasks(int tasks){
this.tasks = tasks;
}
}
这是我的 CategoryResponse 类(我从请求中获取类别列表):
public class CategoryResponse {
private List<Category2> results;
public List<Category2> getResults() {
return results;
}
public void setResults(List<Category2> results) {
this.results = results;
}
}
这是我从我的活动中调用它:
categoryService =
CategoryClient.getClient().create(CategoryService.class);
Call<CategoryResponse> call = categoryService.getProjectCategories(projectId);
call.enqueue(new Callback<CategoryResponse>() {
@Override
public void onResponse(Call<CategoryResponse> call, Response<CategoryResponse> response) {
int statusCode = response.code();
categoriesList2 = new ArrayList<>();
categoriesList2 = response.body().getResults();
}
@Override
public void onFailure(Call<CategoryResponse> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
我需要在请求的标头中添加一个令牌,但是这个令牌会不断变化,所以我不能在我的“@Header”界面上方使用它。有什么方法可以从我的 Activity 中添加此标头?
【问题讨论】:
-
你试过使用拦截器吗?
-
感谢您的回复!我如何使用拦截器来做到这一点?
标签: android http-headers retrofit2