Android Http Login Post

2019-09-16 15:50发布

问题:

I'm trying to make a login to my website via anAndroid app. For some reason it always fail to login.

Here's my login method for the app:


private void login() {

         //this method returns false
         HttpClient httpclient = new DefaultHttpClient();  
         HttpPost httppost = new HttpPost("http://mysite.com/mobileauth.php");
         JSONObject jsonObject = new JSONObject();

           try {  

               List nameValuePairs = new ArrayList(2);  
               jsonObject.put("username", "user1");
               jsonObject.put("password", "12345");

               nameValuePairs.add(new BasicNameValuePair("jsonString", jsonObject.toString()));               

               httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
               HttpResponse response = httpclient.execute(httppost);



               String responseStr = org.apache.http.util.EntityUtils.toString(response.getEntity());
               statusText.setText(responseStr);

           } catch (ClientProtocolException e) {  
               statusText.setText(e.toString());
           } catch (IOException e) {   
               statusText.setText(e.toString());
           } catch (JSONException e) {
               statusText.setText(e.toString());
           }
}

I created a specific file for mobile device login such as Android.

Here's my authentication file on the server:


$host="*"; // Host name 
$username="*"; // Mysql username 
$password="*"; // Mysql password 
$tbl_name="users"; // Table name
$db_name="database";

$link = mysql_connect($host, $username, $password) or die("Connection Error"); 
$db = mysql_select_db("$db_name")or die("Connection Error");

$myusername = $_REQUEST['username']; 
$mypassword = $_REQUEST['password'];

$sql="SELECT * FROM $tbl_name WHERE username='$myusername' AND paswd='$mypassword'";
$result = mysql_query($sql);

$count = mysql_num_rows($result);

if ($count == 1) {
    $timeUpdateQuesry="UPDATE users SET lastLogin=Now() WHERE username='$myusername' AND paswd='$mypassword'";
    mysql_query($timeUpdateQuesry);

    echo("true");
} else {
    //happend without leaving page
    echo ("false");
}

For some reason I always get false in my status TextView.

I'll appreciate any help

Thanks,

回答1:

Remove all the JSON from your android code. You're not receiving it as JSON on the PHP side, so this is probably a root cause. The NameValuePairs should work fine.



回答2:

Your POSTing a JSON object but trying to parse REQUEST variables (i.e. $_GET/$_POST/$_COKIE variables).

Not too sure about the Java but I suspect its assigning the serialized JSON object to a post variable named jsonString. (You could easily check by writing a simple PHP script to dump all of $_POST, $_GET and $HTTP_RAW_POST_DATA)

In which case to get the values in php:

$jsonString=json_decode($_POST['jsonString']);
$myusername = $jsonString['username']; 
$mypassword = $jsonString['password'];