无法显示错误凭证的回应

时间:2018-09-07 10:32:08

标签: android retrofit

我使用Retrofit登录到应用程序并成功完成了(就像我可以成功登录设备一样,响应正常),但是无法显示Toast或Alert对话框以获取错误的凭据。或用户名我想显示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;

    }
}

ApiInteface的代码是:

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);

}

Logcat图像为: enter image description here

1 个答案:

答案 0 :(得分:0)

假设当凭据无效时,登录服务器返回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