为什么在此代码中改造失败?

时间:2016-12-01 12:41:22

标签: android android-studio retrofit

我有一个php服务器,其中包含用户名(jonik)和密码a(123456)作为登录名。我尝试使用我的应用程序进行改造登录,但它始终使用失败方法。服务器必须响应"成功"如果连接发生,对我来说,所以我不知道我做错了什么 - 这是我的代码中的东西吗?

mainactivity

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String myLoginEmailAddress = getLoginEmailAddress();
    TextView loginInformation = (TextView)findViewById(R.id.login_email);
    if(myLoginEmailAddress != null || !myLoginEmailAddress.equals("")){
        loginInformation.setText("Welcome!!! You have logged in as " + myLoginEmailAddress);
    }else {
        loginInformation.setText("Your login email is missing");
    }
}

private String getLoginEmailAddress(){
    String storedEmail = "";
    Intent mIntent = getIntent();
    Bundle mBundle = mIntent.getExtras();
    if(mBundle != null){
        storedEmail = mBundle.getString("EMAIL");
    }
    return storedEmail;
  }
}

loginactivity

public class LoginActivity extends AppCompatActivity {

private final String TAG = "LoginActivity";

public static final String BASE_URL = "http://555.555.555.555";

// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
private TextView failedLoginMessage;

View focusView = null;
private String username;
private String password;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    // Set up the login form.
    mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
    populateAutoComplete();

    failedLoginMessage = (TextView)findViewById(R.id.failed_login);

    mPasswordView = (EditText) findViewById(R.id.password);
    mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
            if (id == R.id.login || id == EditorInfo.IME_NULL) {
                attemptLogin();
                return true;
            }
            return false;
        }
    });

    Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
    mEmailSignInButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            failedLoginMessage.setText("");
            attemptLogin();
        }
    });


    mLoginFormView = findViewById(R.id.login_form);
    mProgressView = findViewById(R.id.login_progress);
}

private void attemptRegistration(){
    boolean mCancel = this.loginValidation();
    if (mCancel) {
        focusView.requestFocus();
    } else {
        registrationProcessWithRetrofit(username, password);
    }
}

private void attemptLogin(){
    boolean mCancel = this.loginValidation();
    if (mCancel) {
        focusView.requestFocus();
    } else {
        loginProcessWithRetrofit(username, password);
    }
}

private boolean loginValidation() {
    // Reset errors.
    mEmailView.setError(null);
    mPasswordView.setError(null);

    // Store values at the time of the login attempt.
    username = mEmailView.getText().toString();
    password = mPasswordView.getText().toString();

    boolean cancel = false;

    // Check for a valid password, if the user entered one.
    if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
        mPasswordView.setError(getString(R.string.error_invalid_password));
        focusView = mPasswordView;
        cancel = true;
    }

    // Check for a valid username address.
    if (TextUtils.isEmpty(username)) {
        mEmailView.setError(getString(R.string.error_field_required));
        focusView = mEmailView;
        cancel = true;
    } /*else if (!isEmailValid(username)) {
        mEmailView.setError(getString(R.string.error_invalid_email));
        focusView = mEmailView;
        cancel = true;
    }*/
    return cancel;
}

private void populateAutoComplete(){
    String[] countries = getResources().getStringArray(R.array.autocomplete);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,countries);
    mEmailView.setAdapter(adapter);
}



private boolean isPasswordValid(String password) {
    //TODO: Replace this with your own logic
    return password.length() > 4;
}

/**
 * Shows the progress UI and hides the login form.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            }
        });

        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mProgressView.animate().setDuration(shortAnimTime).alpha(
                show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            }
        });
    } else {
        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
    }
}

private ApiInterface getInterfaceService() {

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    final ApiInterface mInterfaceService = retrofit.create(ApiInterface.class);
    return mInterfaceService;
}

private void loginProcessWithRetrofit(final String username, String password){

    ApiInterface mApiService = this.getInterfaceService();
    Call<Login> mService = mApiService.authenticate(username, password);
    mService.enqueue(new Callback<Login>() {
        @Override
        public void onResponse(Call<Login> call, Response<Login> response) {

            Login mLoginObject = response.body();
            String returnedResponse = mLoginObject.isLogin;
            Toast.makeText(LoginActivity.this, "Returned " + returnedResponse, Toast.LENGTH_LONG).show();

            //showProgress(false);
            if(returnedResponse.trim().equals("success")){
                // redirect to Main Activity page
                Intent loginIntent = new Intent(LoginActivity.this, MainActivity.class);
                loginIntent.putExtra("EMAIL", username);
                startActivity(loginIntent);
            }
            if(returnedResponse.trim().equals("error")){
                // use the registration button to register
                failedLoginMessage.setText(getResources().getString(R.string.registration_message));
                mPasswordView.requestFocus();
            }
        }

        @Override
        public void onFailure(Call<Login> call, Throwable t) {
            call.cancel();
            Toast.makeText(LoginActivity.this, "Please check your network connection and internet permission", Toast.LENGTH_LONG).show();
        }
    });
}

登录

public class Login {
public String isLogin;
          }

ApiInterface

public interface ApiInterface {
    @FormUrlEncoded
@POST("/cult_tickets/request/login.php")
Call<Login> authenticate(@Field("username") String username, @Field("password") String password);

修改 我在日志中得到了这个,但仍然在登录活动中失败

D/CustomLogRetrofit: <-- 200 OK       http://555.555.555.555/cult_tickets/request/login.php (298ms)
  D/CustomLogRetrofit: Date: Fri, 02 Dec 2016 05:27:47 GMT
  D/CustomLogRetrofit: Server: Apache/2.4.23 (Win32) OpenSSL/1.0.2h   PHP/5.6.24
  D/CustomLogRetrofit: X-Powered-By: PHP/5.6.24
  D/CustomLogRetrofit: Content-Length: 7
  D/CustomLogRetrofit: Keep-Alive: timeout=5, max=100
  D/CustomLogRetrofit: Connection: Keep-Alive
  D/CustomLogRetrofit: Content-Type: text/html; charset=UTF-8
  D/CustomLogRetrofit: success
  D/CustomLogRetrofit: <-- END HTTP (7-byte body)

3 个答案:

答案 0 :(得分:0)

执行以下步骤

步骤1-检查menifeist文件中的权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

步骤2-检查代理设置(如果您的网络中有代理),请检查https://stackoverflow.com/a/18443524/4741746

步骤3-尝试检查postman或restClient的响应是否API工作正常

第4步 - 更改 public static final String BASE_URL =“http://555.555.555.555”;到 Orignal IP地址或LOCALHOST

向我们展示您的清单文件

答案 1 :(得分:0)

这就是你的答案:)你的java对象无法转换为服务器响应。基本上,您的Login对象不是从服务器返回的对象

将http loggin拦截器添加到您的改造中,您将得到您的回复:)

private ApiInterface getInterfaceService() {
      HttpLoggingInterceptor.Logger myLogger = new HttpLoggingInterceptor.Logger() {
        @Override
        public void log(String message) {
            Log.d("CustomLogRetrofit", message);
        }
    };
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(myLogger);
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client =  new OkHttpClient.Builder() 
                        .addInterceptor(loggingInterceptor)
                        .build();



    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    final ApiInterface mInterfaceService = retrofit.create(ApiInterface.class);
    return mInterfaceService;
}

编辑: 这是因为您的服务器没有返回JSON对象。 “成功”只是一个字符串。您可以更改服务器以返回{"isLogin"="success"}之类的内容或使用@Rainmaker解决方案(使用RespondBody)

答案 2 :(得分:0)

尝试

Call<JsonObject> authenticate(@Field("username") String username, @Field("password") String password);

如果你要获得JsonObject

Call<ResponseBody> authenticate(@Field("username") String username, @Field("password") String password);

如果你要获得String