Login to Website not working

Hi I am having trouble making this app login to my website. Here is the php code:

<?php
            session_start();

            include 'api/connect.php';

            $username = mysql_real_escape_string(htmlentities($_POST['username']));
            $password = mysql_real_escape_string(htmlentities(sha1($_POST['password'])));

            $query = mysql_query("SELECT * FROM `beta` WHERE `username` = '" . $username . "' AND `password` = '" . $password . "'") or die(mysql_query());

            // Start the long process
            $rows = mysql_num_rows($query);

            if($rows == 1){     
              while($list = mysql_fetch_assoc($query)) {
                 $output = $list;
                 echo json_encode($output);
              }
              mysql_close();
            }


?>

Here is the android code:

package com.awsomechat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;


import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
 import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

EditText etUser, etPass;
Button blogin;

// Username, Password
String username, password;

// Make an HTTP Client
HttpClient httpclient;
HttpPost httppost;

// Store the username and password in an array
ArrayList<NameValuePair> nameValuePairs;

// HTTP Response & Entity
HttpResponse response;
HttpEntity entity;



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

    initialise();
}

private void initialise() {
    // TODO Auto-generated method stub
    etUser = (EditText) findViewById(R.id.etUser);
    etPass = (EditText) findViewById(R.id.etPass);
    blogin = (Button) findViewById(R.id.etSubmit);
    blogin.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    // The user tapped the Login button, start logging in

    // Default HTTPClient
    httpclient = new DefaultHttpClient();

    // Post the values to the AwsomeChat Login script
    httppost = new HttpPost("http://beta-awsomechat.tk/login.php");

    // THe values we are working with
    username = etUser.getText().toString();
    password = etPass.getText().toString();

    // Try to login. Start the login validation/process
    try {
        nameValuePairs = new ArrayList<NameValuePair>();

        // Store the username and password in an array
        nameValuePairs.add(new BasicNameValuePair("username", username));
        nameValuePairs.add(new BasicNameValuePair("password", password));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        response = httpclient.execute(httppost);

        if(response.getStatusLine().getStatusCode() == 200){

            // Get the info given to us.
            entity = response.getEntity();

            if(entity != null){
                InputStream instream = entity.getContent();

                JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));

                String retUser = jsonResponse.getString("username");
                String retPass = jsonResponse.getString("password");

                // Start the validation process
                if(username.equals(retUser) && password.equals(retPass)){
                    //
                    //
                    SharedPreferences sp = getSharedPreferences("logindetails", 0);

                    SharedPreferences.Editor spedit = sp.edit();

                    spedit.putString("user", username);
                    spedit.putString("pass", password);

                    //
                    spedit.commit();

                    Toast.makeText(getBaseContext(), "Login Success", Toast.LENGTH_SHORT).show();

                } else {
                    Toast.makeText(getBaseContext(), "Login Fialed.", Toast.LENGTH_SHORT).show();
                }
            }
        }
    } catch(Exception e) {
        e.printStackTrace();
        Toast.makeText(getBaseContext(), "Login Failed.", Toast.LENGTH_SHORT).show();
    }
}

private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}


}

For some reason it keeps saying "Login failed" every time. I fixed all the bugs in the php code, it must be the android code because there are no errors in the php code. LogCat says nothing, nor does the Console which makes it harder to find the problem.

**EDIT: I got errors in LogCat:

06-15 16:55:16.400: E/ActivityThread(870): Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40cfaac0 that was originally bound here 06-15 16:55:16.400: E/ActivityThread(870): android.app.ServiceConnectionLeaked: Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40cfaac0 that was originally bound here 06-15 16:55:16.400: E/ActivityThread(870): at android.app.LoadedApk$ServiceDispatcher.(LoadedApk.java:969) 06-15 16:55:16.400: E/ActivityThread(870): at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:863) 06-15 16:55:16.400: E/ActivityThread(870): at android.app.ContextImpl.bindService(ContextImpl.java:1418) 06-15 16:55:16.400: E/ActivityThread(870): at android.app.ContextImpl.bindService(ContextImpl.java:1407) 06-15 16:55:16.400: E/ActivityThread(870): at android.content.ContextWrapper.bindService(ContextWrapp er.java:473) 06-15 16:55:16.400: E/ActivityThread(870): at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:157) 06-15 16:55:16.400: E/ActivityThread(870): at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:145) 06-15 16:55:16.400: E/ActivityThread(870): at com.android.emailcommon.service.ServiceProxy.test(ServiceProxy.java:191) 06-15 16:55:16.400: E/ActivityThread(870): at com.android.exchange.ExchangeService$7.run(ExchangeService.java:1850) 06-15 16:55:16.400: E/ActivityThread(870): at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:551) 06-15 16:55:16.400: E/ActivityThread(870): at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:549) 06-15 16:55:16.400: E/ActivityThread(870): at android.os.AsyncTask$2.call(AsyncTask.java:287) 06-15 16:55:16.400: E/ActivityThread(870): at java.util.concurrent.FutureTask.run(FutureTask.java:234) 06-15 16:55:16.400: E/ActivityThread(870): at java.util.concurrent.Th readPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 06-15 16:55:16.400: E/ActivityThread(870): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 06-15 16:55:16.400: E/ActivityThread(870): at java.lang.Thread.run(Thread.java:856) 06-15 16:55:16.514: E/StrictMode(870): null 06-15 16:55:16.514: E/StrictMode(870): android.app.ServiceConnectionLeaked: Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40cfaac0 that was originally bound here 06-15 16:55:16.514: E/StrictMode(870): at android.app.LoadedApk$ServiceDispatcher.(LoadedApk.java:969) 06-15 16:55:16.514: E/StrictMode(870): at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:863) 06-15 16:55:16.514: E/StrictMode(870): at android.app.ContextImpl.bindService(ContextImpl.java:1418) 06-15 16:55:16.514: E/StrictMode(870): at android.app.ContextImpl.bindService(ContextImpl.java:1407) 06-15 16:55:16.514: E/Strict Mode(870): at android.content.ContextWrapper.bindService(ContextWrapper.java:473) 06-15 16:55:16.514: E/StrictMode(870): at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:157) 06-15 16:55:16.514: E/StrictMode(870): at com.android.emailcommon.service.ServiceProxy.setTask(ServiceProxy.java:145) 06-15 16:55:16.514: E/StrictMode(870): at com.android.emailcommon.service.ServiceProxy.test(ServiceProxy.java:191) 06-15 16:55:16.514: E/StrictMode(870): at com.android.exchange.ExchangeService$7.run(ExchangeService.java:1850) 06-15 16:55:16.514: E/StrictMode(870): at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:551) 06-15 16:55:16.514: E/StrictMode(870): at com.android.emailcommon.utility.Utility$2.doInBackground(Utility.java:549) 06-15 16:55:16.514: E/StrictMode(870): at android.os.AsyncTask$2.call(AsyncTask.java:287) 06-15 16:55:16.514: E/StrictMode(870): at java.util.concurrent.FutureTask.run(FutureTask.java:234) 06-15 16:55:16.514: E/StrictMode (870): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 06-15 16:55:16.514: E/StrictMode(870): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 06-15 16:55:16.514: E/StrictMode(870): at java.lang.Thread.run(Thread.java:856) 06-15 16:55:28.370: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property

This error always pops up in Log Cat when pressing the button to send the login details:

06-15 16:59:44.379: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property**


I assume the problem is your retUser and retPassword. Have you tried debugging to see their value? I suspect they're null and therefore returning false when comparing them to username and password. String's equals methode returns false when the argument is null. This makes the check fail and go the the else-block. Here you show the toast "Login Failed." without printing the stacktrace to LogCat or the Console.

I'd first of all debug the PHP code and see if it actually returns the JSON encoded message. If so, make sure you convert the bytestream correctly to the JSONObject.

EDIT

As I read in one of your comments, you've hashed the password using PHP before storing it in the DB. Herefore you will need to hash the inputted password using the same hashing algoritme in java and afterwards compare the hashes. If they are equal, the provided password is the same as the one retrieved from the DB.

链接地址: http://www.djcxy.com/p/80010.html

上一篇: Android将HTTP连接到MVC Asp.net控制器

下一篇: 登录到网站无法正常工作