dsiftnc99059 2016-08-25 06:31
浏览 64

使用Httpclient进行Android登录

i am newbie in android application for using php, json, mysql and httpclient. i am trying to make a register and login application. in Register, have successfully. but when login i have a problem. every input email and password always give an error "Invalid email or password". Even i was input a right email and password. the code is below.

login1.php

<?php
define('HOST','mxxxx.xxxxx.com');
define('USER','xxxxxx');
define('PASS','xxxxx');
define('DB','xxxxxx');

$con = mysqli_connect(HOST,USER,PASS,DB);

$emailAddress = $_POST['email'];
$passWord = $_POST['password'];

$sql = "select * from user where email='$emailAddress' and password='$passWord'";

$res = mysqli_query($con,$sql);

$check = mysqli_fetch_array($res);

if(isset($check)){
echo 'success';
}else{
echo 'failure';
}

mysqli_close($con);
?>

then the LoginActivity.class (in eclipse)

public class LoginActivity extends Activity{

    public static final String KEY_EMAIL="emailAddress";
    public static final String KEY_PASSWORD="passWord";

    private EditText etPassword, etEmail;
    String passWord,emailAddress,email;
    Button login;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
        etEmail=(EditText)findViewById(R.id.ET_email);
        etPassword=(EditText)findViewById(R.id.ET_password);
        login=(Button)findViewById(R.id.btnLogin);

        login.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                //fullName= etFullName.getText().toString();
                passWord=etPassword.getText().toString();
                emailAddress=etEmail.getText().toString();

                if (!isValidEmail(emailAddress)) {
                    etEmail.setError("Please Enter Valid Email");
                    etEmail.requestFocus();
                }
                else if (!isValidPassword(passWord)){
                    etPassword.setError("Password min. 6 characters");
                    etPassword.requestFocus();
                }else{

                    //new LoginAsync().execute(emailAddress,passWord);

                    login(emailAddress,passWord);
                    // new BackgroundTaskLogin(LoginActivity.this).execute(emailAddress,passWord );
                      etEmail.setText("");
                      etPassword.setText("");
                }

            }
    });
        // Listening to register new account link
        registerScreen.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // Switching to Register screen
                Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
                startActivity(i);
            }
        });
    }

   private void login(final String emailAddress, final String passWord) {
     class LoginAsync extends AsyncTask<String, Void, String>{
         //private Context context;
            public static final String KEY_EMAIL = "email";
            private Dialog loadingDialog;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loadingDialog = ProgressDialog.show(LoginActivity.this, "Please wait", "Loading...");
            }

            @Override
            protected String doInBackground(String... params) {
                String emailAddress = params[0];
                String passWord = params[1];

                InputStream is = null;
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("email", emailAddress));
                nameValuePairs.add(new BasicNameValuePair("password", passWord));
                //return nameValuePairs;

                String result = null;

                try{
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost("http://xxxx.com/login1.php");
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpClient.execute(httpPost);
                    HttpEntity entity = response.getEntity();

                    is = entity.getContent();

                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "
");
                    }
                    result = sb.toString();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return result;
            }

            @Override
            protected void onPostExecute(String result){
                String s = result.trim();
                loadingDialog.dismiss();
                if(s.equalsIgnoreCase("success")){
                    Intent intent = new Intent(LoginActivity.this, ActivityUserProfile.class);
                    intent.putExtra(KEY_EMAIL, emailAddress);
                    startActivity(intent);
                    finish();

                }else {
                     Toast.makeText(getApplicationContext(), "Invalid Email or Password", Toast.LENGTH_LONG).show();
              }}
        }

     new LoginAsync().execute(emailAddress, passWord);

    }


    private boolean isValidEmail(String email) {
        String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
                + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

        Pattern pattern = Pattern.compile(EMAIL_PATTERN);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }

    // validating password with retype password
    private boolean isValidPassword(String pass) {
        if (pass != null && pass.length() >= 6) {
            return true;
        }
        return false;
    }

        }
  • 写回答

1条回答 默认 最新

  • douyong6585 2016-08-25 06:49
    关注
    httpPost.setEntity(new StringEntity(body, HTTP.UTF_8));
    

    or

    HttpPost httpPost = new HttpPost("http://someurl.com");
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8));
    

    Refer 1

    Refer 2

    评论

报告相同问题?

悬赏问题

  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导
  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp
  • ¥15 学不会递归,理解不了汉诺塔参数变化
  • ¥15 基于图神经网络的COVID-19药物筛选研究
  • ¥30 软件自定义无线电该怎样使用