我使用改装库通过api向服务器发出post请求,发送用户名和密码,并获得会话令牌作为响应。我使用这个令牌(在头中作为承载令牌)向服务器发送纬度和经度的post以获取数据,但是该方法在enqueue()的onfailure方法中重复结束。
@POST("api/auth/login/username/{username}/password/{password}")
Call<ResponseBody> login(@Path("username")String username, @Path("password")String password);
@POST("api/products/get")
Call<ResponseBody> getData(@Header("Authorization") String authorization);Call<ResponseBody>
主要活动:
Retrofit.Builder builder=new Retrofit.Builder()
.baseUrl("fake url")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit=builder.build();
DataApi companyApi=retrofit.create(DataApi.class);
private String Token="";tokenCall=comapnyApi.login("data","!fakedata");
tokenCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()){
try {
Toast.makeText(MainActivity.this, response.body().string(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
else {
Toast.makeText(MainActivity.this, "Wrong Username and password", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, "Couldn't connect to Fake company Server Api", Toast.LENGTH_SHORT).show();
}
});
Call<ResponseBody> Data=companyApi.getData(Token);
Data.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()){
try {
Toast.makeText(MainActivity.this, response.body().string(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
else {
Toast.makeText(MainActivity.this, "Api Token Expired", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, "Couldn't connect to Fake Company Server", Toast.LENGTH_SHORT).show();
}
});
1条答案
按热度按时间hgqdbh6s1#
我想是因为你在第一个请求之后才提出第二个请求。enqueue是异步的,所以当您执行第一个请求时,我指的是tokencall.enqueue(),它的响应会在后面出现,因此第二个api调用或data.enqueue()会用token==“”调用。因此,在第一个api调用的onresponse中进行第二个api调用。