这是我目前使用Retrofit 2.0进行API CALL的代码并且工作正常
private void getWallet(String api_key) {
final ProgressDialog loading = new ProgressDialog(ActivityWallet.this, R.style.MyTheme);
loading.setCancelable(true);
loading.show();
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(Constants.BASERESTURL)
.client(httpClient)
.build();
EndPoints apiOrders = retrofit.create(EndPoints.class);
Call<ArrayList<Order>> call = apiOrders.getWallet(api_key);
call.enqueue(new Callback<ArrayList<Order>>() {
@Override
public void onResponse(Response<ArrayList<Order>> response, Retrofit retrofit) {
loading.dismiss();
ArrayList<Order> orders = response.body();
Utility.setOrders(orders);
AdapterOrder adapter = new AdapterOrder(getApplicationContext(), Utility.getOrders());
orderListView.setAdapter(adapter);
}
@Override
public void onFailure(Throwable t) {
Utility.displaySnackBar(coordinatorLayout, "INTERNET CONNECTION LOST");
loading.dismiss();
}
});
}
现在我需要在请求中添加标头。谷歌搜索后我才知道我可以使用okhttp。我创建了如下新代码,在请求中添加标头:
private void getWallet(String api_key) {
final ProgressDialog loading = new ProgressDialog(ActivityWallet.this, R.style.MyTheme);
loading.setCancelable(true);
loading.show();
OkHttpClient httpClient = new OkHttpClient();
httpClient.networkInterceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("test", "test").build();
return chain.proceed(request);
}
});
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(Constants.BASERESTURL)
.client(httpClient)
.build();
EndPoints apiOrders = retrofit.create(EndPoints.class);
Call<ArrayList<Order>> call = apiOrders.getWallet(api_key);
call.enqueue(new Callback<ArrayList<Order>>() {
@Override
public void onResponse(Response<ArrayList<Order>> response, Retrofit retrofit) {
loading.dismiss();
ArrayList<Order> orders = response.body();
Utility.setOrders(orders);
AdapterOrder adapter = new AdapterOrder(getApplicationContext(), Utility.getOrders());
orderListView.setAdapter(adapter);
}
@Override
public void onFailure(Throwable t) {
Utility.displaySnackBar(coordinatorLayout, "INTERNET CONNECTION LOST");
loading.dismiss();
}
});
}
但它在此行返回chain.proceed(request);
中给出了编译错误required: retrofit.Response
found: com.squareup.okhhtp.Response
将导入更改为com.squareup.okhhtp.Response后,在改进响应中看到很多错误。
任何人都可以帮助我,我做错了吗?如何解决?