我正在实施登录Web服务。如果用户的电子邮件和密码正确,我会收到正确的答复。但如果电子邮件或密码不正确,我将无效。如果电子邮件或密码不正确,我想从服务器发送消息。我的代码如下。
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);
}
不成功的登录响应是:
{“success”:false,“message”:“用户名或密码不正确。” }
成功的回应是:
{“success”:true,“message”:“”,“data”:{“token”:“”,“name”:“Gmail”,“picture”:“”,“userid”:60,“phone” :“(111)114-4444”,“email”:“[email protected]”,“company_name”:null,“st_address”:“Gmail帐户,卫星”,“location_id”:1,“account_type”:2 }}
即使呼叫失败,如果你收到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
}
这里有很多事情要做。让我们从为什么需要手动反序列化开始。 Retrofit不会自动为您转换错误正文,您需要自己完成。在这里,我选择创建一个不优雅的Gson
实例,但却有用。
我也选择使用string()
。此方法将整个响应读入内存,并且可能会因大响应而崩溃。调用它会耗尽okhttp缓冲区,这意味着你将无法再次调用它(据我所知),所以如果你想多次使用它,请将它保存在变量中。
希望这可以帮助