1、访问的PHP文件
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["username"]) && isset($_GET["password"])) {
$username = $_GET['username'];
$password = $_GET["password"];
// get a product from products table
$result = mysql_query("SELECT * FROM tb_userlogin WHERE username = \"$username\" AND userpwd = \"$password\"");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
// success
$response["success"] = 1;
$response["message"] = "Get the user";
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 2;
$response["message"] = "No user found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 3;
$response["message"] = "Error in query!";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 4;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
PHP连接的工具文件
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
// Selecing database
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}
}
?>
2、JSONParser工具文件(主要定义POST和GET方法)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url = url + "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
3、定义异步执行任务(与界面交互的事务要在onPostExecute中做,且要在UI线程中运行)
class LoginOn extends AsyncTask<String, String, String> {
private JSONObject json;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("正在登录,请稍候...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", strUsername));
params.add(new BasicNameValuePair("password", strPassword));
json = jsonParser.makeHttpRequest(Parameters.URL_LOGIN, "GET", params);
return null;
}
@Override
protected void onPostExecute(String s) {
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
int success = json.getInt(Parameters.TAG_SUCCESS);
String message = json.getString(Parameters.TAG_MESSAGE);
if (1 == success) {
Toast.makeText(cContext, "登录成功 :-)", Toast.LENGTH_SHORT).show();
// start show activity
Intent intentShowPassword = new Intent(cContext, ShowPasswordActivity.class);
Bundle mBundle = new Bundle();
mBundle.putString("username", username);
intentShowPassword.putExtras(mBundle);
startActivity(intentShowPassword);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
pDialog.dismiss();
super.onPostExecute(s);
}
}
4、调用异步执行任务
new LoginOn().execute();
5、安装AppServ注意点:
(1)PhpMyAdmin的登录密码。首次登陆时,可以使用用户名为admin密码为空登录;后来登录需要使用设置的密码,用户名为root。
(2)Apache访问是好的,但是打不开PhpMyAdmin,解决办法:
①修改phpmyadmin/config.inc.php中的 $cfg['Servers'][$i]['host'] = 'localhost'; 为 $cfg['Servers'][$i]['host'] = '127.0.0.1';
②禁用IPV6并在host文件中的 ::1 localhost 前加上 #。
参考:http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/