通过Android应用程序连接到localhost服务器上的PHP脚本

时间:2015-08-02 14:52:18

标签: php android localhost

我试图为我的Android应用程序创建一个登录活动,我在对话框中说“尝试登录”。但该应用程序很快就会强行关闭。我会发布代码,任何帮助表示赞赏!

package com.fr31ght.etched;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class LoginActivity extends Activity implements OnClickListener{

private EditText user, pass;
private Button Loginbtn;

//process dialog 
private ProgressDialog pDialog;

//JSON parser class 
JSONParser jsonParser = new JSONParser();

//php script location 
private static final String LOGIN_URL = 
"http://127.0.0.1//android-     login/login.php";

//JSON element id's from php script
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";




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

    //set up input fields
    user = (EditText)findViewById(R.id.username);
    pass = (EditText)findViewById(R.id.password);

    //Set up buttons 
    Loginbtn = (Button)findViewById(R.id.loginbtn);

    //Register Listeners
    Loginbtn.setOnClickListener(this);


}


@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

    switch (v.getId()){
    case R.id.loginbtn:
        new AttemptLogin().execute();
        break;

        default:
            break;
    }


}

class AttemptLogin extends AsyncTask<String, String, String>{

    //Show progress dialog 
    boolean failure = false;

    protected void onPreExecute(){

        super.onPreExecute();

        pDialog = new ProgressDialog(LoginActivity.this);
        pDialog.setMessage("Attempting Login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @SuppressWarnings("deprecation")
    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub

        //check for success tag 

        int success;
        String username = user.getText().toString();
        String password = pass.getText().toString();

        try{
            //Building parmeters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));

            Log.d("request!", "Starting");
            //Getting product details with HTTP REQUEST
            JSONObject json = jsonParser.makeHttpRequest
            (LOGIN_URL, "POST", params);

            //check log for json response
            Log.d("Login attempt", json.toString());

            //Json Success tag 
            success = json.getInt(TAG_SUCCESS);
            if (success == 1){
                Log.d("Login Successful!", json.toString());
                Intent i = new Intent(LoginActivity.this, Etched.class);
                finish();
                startActivity(i);
                return json.getString(TAG_MESSAGE);

            }

        } catch (JSONException e){
            e.printStackTrace();
        }

        return null;



    }

     protected void onPostExecute(String file_url){

        //dismiss the dialog 
        pDialog.dismiss();
        if(file_url !=null){

            Toast.makeText(LoginActivity.this, file_url, Toast.LENGTH_LONG) 
            .show();
          }

      }


   }










  }

PHP代码

<?php
error_reporting(1);

//load and connect to MySQL database stuff
include('config.php');


if (!empty($_POST)) {

 //gets user's info based off of a username.

 $query = "SELECT id, username, password FROM users WHERE username 
 = :username";



$query_params = array(

    ':username' => $_POST['username']

 );



try {

    $stmt   = $db->prepare($query);

    $result = $stmt->execute($query_params);

 }

 catch (PDOException $ex) {

    // For testing, you could use a die and message.

    //die("Failed to run query: " . $ex->getMessage());



    //or just use this use this one to product JSON data:

    $response["success"] = 0;

    $response["message"] = "Database Error1. Please Try Again!";

    die(json_encode($response));



}



//This will be the variable to determine whether or not the 
 user's       information is correct.

  //we initialize it as false.

$validated_info = false;



//fetching all the rows from the query

$row = $stmt->fetch();

if ($row) {

    //if we encrypted the password, we would unencrypt it here, but in 
    our case we just

    //compare the two passwords

    if ($_POST['password'] === $row['password']) {

        $login_ok = true;

    }

  }



  // If the user logged in successfully, then we send them to the private 
   members-only page

  // Otherwise, we display a login failed message and show the login form  
  again

if ($login_ok) {
    $response["success"] = 1;

    $response["message"] = "Login successful!";

    echo('successful!!');

    die(json_encode($response));

} else {

    $response["success"] = 0;

    $response["message"] = "Invalid Credentials!";

    echo('unsuccessful!!');

    die(json_encode($response));
  }

  } else {
 ?>

    <h1>Login</h1>
    <form action="login.php" method="post">

        Username:<br />

        <input type="text" name="username" placeholder="username" />

        <br /><br />

        Password:<br />

        <input type="password" name="password" placeholder="password"   
        value="" />

        <br /><br />

        <input type="submit" value="Login" />

      </form>

    <a href="register.php">Register</a>

  <?php

  }
  ?>

1 个答案:

答案 0 :(得分:0)

在你的asynctask尝试这样做:

// Set connection
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(LOGIN_URL);

// Add parameters
List<NameValuePair> data = new ArrayList<NameValuePair>(2);
data.add(new BasicNameValuePair("username", username));
data.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(data));
ResponseHandler<String> responseHandler = new BasicResponseHandler();

//Here you get the response from server
String response = httpclient.execute(httppost,responseHandler);

我在我的应用程序中使用它没有任何问题。