//这是JSONParser,用来解析JSON
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; //JSON基本单元,包含键值对,new JSONObject().put("JSON", "Hello, World!") 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); //初始化POST请求 httpPost.setEntity(new UrlEncodedFormEntity(params)); //设置实体 HttpResponse httpResponse = httpClient.execute(httpPost); //执行客户端的POST请求,返回一个响应 HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); //获取响应内容--InputStream }else if(method == "GET"){ // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); //客户端 String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); //初始化GET请求 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(); } //将InputStream转换成String格式的内容 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; } }
要使用的话在需要使用的地方插入下列函数
/** 要是添加Product */ Private addNewProduct(String name,String price,String desc,String URL){ List<NameValuePairs> params = new ArrayList<NameValuePairs>();//使用键值对来添加变量 params.add(new BasicNameValuePair("name",name)); params.add(new BasicNameValuePair("price",price)); params.add(new BasicNameValuePair("description",desc)); JSONObject json = JSONParser.makeHttpRequest(URL,"POST",params); } /** * getting All products from url * */ protected String getAllProduct(String... args) { // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); // getting JSON string from URL JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params); try { // Checking for SUCCESS TAG int success = json.getInt(TAG_SUCCESS); if (success == 1) { existaProduse = true; products = json.getJSONArray(TAG_PRODUCTS); // looping through All Products for (int i = 0; i < products.length(); i++) { JSONObject c = products.getJSONObject(i); // Storing each json item in variable String id = c.getString(TAG_PID); String name = c.getString(TAG_NAME); String price = c.getString(TAG_PRICE).concat("$"); String description = c.getString(TAG_DESCRIPTION); // creating new HashMap HashMap<String, String> map = new HashMap<String, String>(); // adding each child node to HashMap key => value map.put(TAG_PID, id); map.put(TAG_NAME, name); map.put(TAG_PRICE, price); map.put(TAG_DESCRIPTION, description); productsList.add(map); } } } catch (JSONException e) { e.printStackTrace(); } return null; }
接下来是PHP函数,可以使用openshift免费服务器来测试,插入一下:openshift服务器是开源的服务器,可以免费部署三个应用,包括java,Python,php都支持,只不过服务器在国外,速度稍微慢一点,要是有钱可以使用sina云服务
数据库使用的Mysql。
先创建products表,然后创建四个变量:
pid:自增长的int类型变量
name:varchar(20)
price:varchar(10)
description:varchar(100)
//db_config.php <?php /* * All database connection variables */ $DB_HOST = getenv(\'OPENSHIFT_MYSQL_DB_HOST\'); $DB_PORT = getenv(\'OPENSHIFT_MYSQL_DB_PORT\'); $DB_USER = "adminrzQntWs"; $DB_PASSWORD = "h1KPiiBD-Gw6"; define(\'DB_USER\', $DB_USER); // db user define(\'DB_PASSWORD\', $DB_PASSWORD); // db password (mention your db password here) define(\'DB_DATABASE\', "androidhive"); // database name define(\'DB_SERVER\', $DB_HOST.":".$DB_PORT); // db server ?>
//create_product.php <?php /* * Following code will create a new product row * All product details are read from HTTP Post Request */ // array for JSON response $response = array(); // check for required fields if (isset($_POST[\'name\']) && isset($_POST[\'price\']) && isset($_POST[\'description\'])) { $name = $_POST[\'name\']; $price = $_POST[\'price\']; $description = $_POST[\'description\']; // include db connect class require_once __DIR__ . \'/db_connect.php\'; // connecting to db $db = new DB_CONNECT(); // mysql inserting a new row $result = mysql_query("INSERT INTO products(name, price, description) VALUES(\'$name\', \'$price\', \'$description\')"); // check if row inserted or not if ($result) { // successfully inserted into database $response["success"] = 1; $response["message"] = "Product successfully created."; // echoing JSON response echo json_encode($response); } else { // failed to insert row $response["success"] = 0; $response["message"] = "Oops! An error occurred."; // echoing JSON response echo json_encode($response); } } else { // required field is missing $response["success"] = 0; $response["message"] = "Required field(s) is missing"; // echoing JSON response echo json_encode($response); } ?>
//get_all_products.php <?php /* * Following code will list all the products */ // array for JSON response $response = array(); // include db connect class require_once __DIR__ . \'/db_connect.php\'; // connecting to db $db = new DB_CONNECT(); // get all products from products table $result = mysql_query("SELECT *FROM products") or die(mysql_error()); // check for empty result if (mysql_num_rows($result) > 0) { // looping through all results // products node $response["products"] = array(); while ($row = mysql_fetch_array($result)) { // temp user array $product = array(); $product["pid"] = $row["pid"]; $product["name"] = $row["name"]; $product["price"] = $row["price"]; $product["description"] = $row["description"]; $product["created_at"] = $row["created_at"]; $product["updated_at"] = $row["updated_at"]; // push single product into final response array array_push($response["products"], $product); } // success $response["success"] = 1; // echoing JSON response echo json_encode($response); } else { // no products found $response["success"] = 0; $response["message"] = "No products found"; // echo no users JSON echo json_encode($response); } ?>
//update_product.php <?php /* * Following code will update a product information * A product is identified by product id (pid) */ // array for JSON response $response = array(); // check for required fields if (isset($_POST[\'pid\']) && isset($_POST[\'name\']) && isset($_POST[\'price\']) && isset($_POST[\'description\'])) { $pid = $_POST[\'pid\']; $name = $_POST[\'name\']; $price = $_POST[\'price\']; $description = $_POST[\'description\']; // include db connect class require_once __DIR__ . \'/db_connect.php\'; // connecting to db $db = new DB_CONNECT(); // mysql update row with matched pid $result = mysql_query("UPDATE products SET name = \'$name\', price = \'$price\', description = \'$description\' WHERE pid = $pid"); // check if row inserted or not if ($result) { // successfully updated $response["success"] = 1; $response["message"] = "Product successfully updated."; // echoing JSON response echo json_encode($response); } else { } } else { // required field is missing $response["success"] = 0; $response["message"] = "Required field(s) is missing"; // echoing JSON response echo json_encode($response); } ?>
//get_product_detail.php <?php /* * Following code will get single product details * A product is identified by product id (pid) */ // array for JSON response $response = array(); // include db connect class require_once __DIR__ . \'/db_connect.php\'; // connecting to db $db = new DB_CONNECT(); // check for post data if (isset($_GET["pid"])) { $pid = $_GET[\'pid\']; // get a product from products table $result = mysql_query("SELECT *FROM products WHERE pid = $pid"); if (!empty($result)) { // check for empty result if (mysql_num_rows($result) > 0) { $result = mysql_fetch_array($result); $product = array(); $product["pid"] = $result["pid"]; $product["name"] = $result["name"]; $product["price"] = $result["price"]; $product["description"] = $result["description"]; $product["created_at"] = $result["created_at"]; $product["updated_at"] = $result["updated_at"]; // success $response["success"] = 1; // user node $response["product"] = array(); array_push($response["product"], $product); // echoing JSON response echo json_encode($response); } else { // no product found $response["success"] = 0; $response["message"] = "No product found"; // echo no users JSON echo json_encode($response); } } else { // no product found $response["success"] = 0; $response["message"] = "No product found"; // echo no users JSON echo json_encode($response); } } else { // required field is missing $response["success"] = 0; $response["message"] = "Required field(s) is missing"; // echoing JSON response echo json_encode($response); } ?>
//db_connect.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(); } } ?>
//delete_product.php <?php /* * Following code will delete a product from table * A product is identified by product id (pid) */ // array for JSON response $response = array(); // check for required fields if (isset($_POST[\'pid\'])) { $pid = $_POST[\'pid\']; // include db connect class require_once __DIR__ . \'/db_connect.php\'; // connecting to db $db = new DB_CONNECT(); // mysql update row with matched pid $result = mysql_query("DELETE FROM products WHERE pid = $pid"); // check if row deleted or not if (mysql_affected_rows() > 0) { // successfully updated $response["success"] = 1; $response["message"] = "Product successfully deleted"; // echoing JSON response echo json_encode($response); } else { // no product found $response["success"] = 0; $response["message"] = "No product found"; // echo no users JSON echo json_encode($response); } } else { // required field is missing $response["success"] = 0; $response["message"] = "Required field(s) is missing"; // echoing JSON response echo json_encode($response); } ?>
需要使用的朋友可以留言,只发送Android客户端,php文件直接粘贴吧,还需要根据自身情况修改配置一下。