使用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;
    }

        }
douqulv6059
douqulv6059 你能不能帮助我,怎么做?
大约 4 年之前 回复
doupu1949
doupu1949 您是否尝试在进行登录服务调用时记录您作为参数传递的值?如果没有那么请检查他们是否通过了正确的值?
大约 4 年之前 回复
ds342222222
ds342222222 警告:使用mysqli时,您应该使用参数化查询和bind_param将用户数据添加到查询中。不要使用字符串插值或连接来完成此操作,因为您已经创建了严重的SQL注入错误。永远不要将$_POST或$_GET数据直接放入查询中,如果有人试图利用您的错误,这可能是非常有害的。
大约 4 年之前 回复

1个回答



  httpPost.setEntity(new StringEntity(body,HTTP.UTF_8)); 
</ code> </ pre>

或</ p>

  HttpPost httpPost = new HttpPost(“http://someurl.com”); 
httpPost.setEntity(new urlEncodedFormEntity(nameValuePair,HTTP) .UTF_8));
</ code> </ pre>

参考1 </ p>

参考2 </ p>
</ div>

展开原文

原文

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

duanqiao2006
duanqiao2006 仍然是相同的输出@Karthik
大约 4 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐