我正在实现登录Web服务。如果用户的电子邮件和密码正确,我将得到正确的答复。但是如果电子邮件或密码不正确,我将得到null。如果电子邮件或密码不正确,我想从服务器发送消息。我的代码在下面。
Call<LoginResponse> call = RetrofitClient.getInstance().getApi().userLogin(email, password);
call.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
LoginResponse loginResponse = response.body();
System.out.println("body " + response.body());
System.out.println("response " + response.errorBody().toString());
sharedPrefManager.cancelDialog();
if (loginResponse != null) {
if (loginResponse.getSuccess()) {
sharedPrefManager.saveUser(loginResponse.getData(), password);
Intent intent = new Intent(SignIn.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else {
Toast.makeText(SignIn.this, loginResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
SharedPrefManager.getInstance(SignIn.this).cancelDialog();
Toast.makeText(SignIn.this, response.message(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
sharedPrefManager.cancelDialog();
t.printStackTrace();
}
});
public class RetrofitClient {
private static final String BASE_URL = "my_base_url";
private static RetrofitClient mInstance;
private Retrofit retrofit;
OkHttpClient client = new OkHttpClient.Builder()
//.addInterceptor(new SpeechRecognitionIntercepter())
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS).build();
private RetrofitClient() {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public static synchronized RetrofitClient getInstance() {
if (mInstance == null) {
mInstance = new RetrofitClient();
}
return mInstance;
}
public Apis getApi() {
return retrofit.create(Apis.class);
}
}
public interface Apis {
@FormUrlEncoded
@POST("login")
Call<LoginResponse> userLogin(@Field("email") String email, @Field("password") String password);
}
失败的登录响应是:
{ “成功”:错误, “消息”:“用户名或密码不正确。” }
成功的响应是:
{ “成功”:是的, “信息”: ””, “数据”:{ “ token”:“”, “ name”:“ Gmail”, “ picture”:“”, “用户名”:60, “ phone”:“(111)114-4444”, “电子邮件”:“ tahir123@gmail.com”, “ company_name”:null, “ st_address”:“ Gmail帐户,卫星”, “ location_id”:1, “帐户类型”:2 } }
答案 0 :(得分:0)
即使调用失败,从代码中还不清楚是否收到200状态,但是从您的描述看来,您似乎会收到另一个http状态代码。
如果是这种情况,则Retrofit仍将调用onResponse
方法,但是response.isSuccessful()
为false,并且可以通过response.errorBody()
方法访问该正文。
一个简单的方法是:
if(response.isSuccessful())
// Do what you are doing
else {
Gson gson = new Gson();
LoginResponse error = gson.fromJson(response.errorBody().string());
// Use the error variable now
}
这里有很多事情。让我们从为什么需要手动反序列化开始。改造不会自动为您转换错误体,您需要自己进行。在这里,我选择创建一个Gson
实例,它虽然不雅致,但却可以达到目的。
我还选择使用string()
。此方法将整个响应读入内存,并且对于大响应可能会崩溃。调用它将耗尽okhttp缓冲区,这意味着(据我所知)您将无法再次调用它,因此,如果要多次使用它,请将其保留在变量中。
希望这会有所帮助