我正在使用 Retrofit 登录应用程序并成功登录(就像我可以成功登录设备一样,响应正常),但无法显示错误凭据的 Toast 或警报对话框。就像如果有人提供了错误的密码或用户名一样,我想显示 API 的响应“密码或用户名不正确”。我几乎尝试了所有方法,但每次都会收到“超时”消息。此外,Toast 在该活动的其他任何地方都工作正常,但无法应用它来获取错误凭据的响应。
这是我的登录活动代码:
package com.vshine.neuron.riseshine.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.vshine.neuron.riseshine.R;
import com.vshine.neuron.riseshine.util.SessionManager;
import com.vshine.neuron.riseshine.webservice.ApiClient;
import com.vshine.neuron.riseshine.webservice.ApiInterface;
import com.vshine.neuron.riseshine.webservice.apimodel.login.LoginResponse;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class LoginActivity extends AppCompatActivity {
Button login_button;
ImageButton GetRegistered;
EditText userName_edt, password_edt;
String user_name, password;
SessionManager sessionManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sessionManager = new SessionManager(LoginActivity.this);
if (sessionManager.isLoggedIn()) {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
this.finish();
} else {
initBasic();
initLogin();
}
}
private void initBasic() {
login_button = findViewById(R.id.login_button);
GetRegistered = findViewById(R.id.register);
userName_edt = findViewById(R.id.user_name);
password_edt = findViewById(R.id.password);
}
private void initLogin() {
GetRegistered.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, RegisteredActivity.class);
startActivity(intent);
}
});
login_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
user_name = userName_edt.getText().toString();
password = password_edt.getText().toString();
if (validateLogin(user_name, password)) {
//do login
doLogin(user_name, password);
}
}
});
}
private boolean validateLogin(String user_name, String password) {
if (user_name == null || user_name.trim().length() == 0) {
Toast.makeText(this, "Username is required", Toast.LENGTH_SHORT).show();
return false;
}
if (password == null || password.trim().length() == 0) {
Toast.makeText(this, "Password is required", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
private void doLogin(final String username, final String password) {
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<LoginResponse> call = apiService.Login(username, password);
call.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
LoginResponse loginresponse = response.body();
if (!loginresponse.getStatus()) {
/* AlertDialog alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("message");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();*/
Toast.makeText(LoginActivity.this, response.code() + "response", Toast.LENGTH_SHORT).show();
} else {
String id = loginresponse.getResponse().getId();
String userName = loginresponse.getResponse().getUsername();
String firstName = loginresponse.getResponse().getFirstName();
String lastName = loginresponse.getResponse().getLastName();
String email = loginresponse.getResponse().getEmail();
sessionManager.createLoginSession(id, userName, email, firstName, lastName);
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
// Log error here since request failed
Log.e("", t.toString());
}
});
}
}
这是 ApiClient 的代码:
package com.vshine.neuron.riseshine.webservice;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ApiClient {
public static final String BASE_URL = "http://........../vshine/API/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.build();
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
ApiInterface 的代码是:
package com.vshine.neuron.riseshine.webservice;
import com.google.gson.JsonObject;
import com.vshine.neuron.riseshine.webservice.apimodel.login.LoginResponse;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
public interface ApiInterface {
@FormUrlEncoded
@POST("api.php?action=Login")
Call<LoginResponse> Login(@Field("user_name") String username, @Field("password") String password);
}
假设您的登录服务器在凭据无效时返回 401 Unauthorized,您需要检查 onResponse 中的状态代码。
call.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
if (response.code() == 401) {
// show error toast
return;
}
LoginResponse loginresponse = response.body();
if (!loginresponse.getStatus()) {
此外,如果您需要响应正文,由于 401 是不成功的响应,您将在
response.errorBody()
而不是 response.body()
中获得正文。请参阅https://square.github.io/retrofit/2.x/retrofit/retrofit2/Response.html