我正在获取 JSON 编码数据和其他数据作为数据库对我的 android 应用程序的响应
I'm getting the JSON encoded data with other data as a response from the database to a my android app
我是 android 和 PHP 的初学者
我正在尝试将我的 android 应用程序连接到 Wamp 数据库服务器
我正在这里学习这门课程
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
想法是使用 PHP 代码执行基本 SQL 操作
我有 activity 需要产品名称、价格和描述
并将其存储在数据库中,返回带有信息的 JSON 编码数据
关于插入成功与否
但是我在尝试从中创建 JSON对象时遇到错误
这就是我尝试过的
Log.e("JSON",json);
我使用日志查看数据是什么,这是我得到的
05-26 15:25:56.164 7801-7886/products.android.com.connectingproducts E/JSON: <br />
<font size='1'><table class='xdebug-error xe-deprecated' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
<tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp64\www\android_connect\db_connect.php on line <i>28</i></th></tr>
<tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
<tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
<tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0007</td><td bgcolor='#eeeeec' align='right'>241312</td><td bgcolor='#eeeeec'>{main}( )</td><td title='C:\wamp64\www\android_connect\create_product.php' bgcolor='#eeeeec'>...\create_product.php<b>:</b>0</td></tr>
<tr><td bgcolor='#eeeeec' align='center'>2</td><td bgcolor='#eeeeec' align='center'>0.0012</td><td bgcolor='#eeeeec' align='right'>252032</td><td bgcolor='#eeeeec'>DB_CONNECT->__construct( )</td><td title='C:\wamp64\www\android_connect\create_product.php' bgcolor='#eeeeec'>...\create_product.php<b>:</b>22</td></tr>
<tr><td bgcolor='#eeeeec' align='center'>3</td><td bgcolor='#eeeeec' align='center'>0.0012</td><td bgcolor='#eeeeec' align='right'>252120</td><td bgcolor='#eeeeec'>DB_CONNECT->connect( )</td><td title='C:\wamp64\www\android_connect\db_connect.php' bgcolor='#eeeeec'>...\db_connect.php<b>:</b>11</td></tr>
<tr><td bgcolor='#eeeeec' align='center'>4</td><td bgcolor='#eeeeec' align='center'>0.0016</td><td bgcolor='#eeeeec' align='right'>252936</td><td bgcolor='#eeeeec'><a href='http://www.php.net/function.mysql-connect' target='_new'>mysql_connect</a>
( )</td><td title='C:\wamp64\www\android_connect\db_connect.php' bgcolor='#eeeeec'>...\db_connect.php<b>:</b>28</td></tr>
</table></font>
{"success":1,"message":"Product successfully created."}
得到的数据似乎有一些 html 风格的代码,最后它有我想要的消息:
{"success":1,"message":"Product successfully created."}
所以这是我的JSON解析器代码
package products.android.com.connectingproducts;
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;
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.equals("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.equals("GET")){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
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());
}
Log.e("JSON",json);
// 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;
}
}
这是我的 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);
}
?>
如果您知道为什么将此数据添加到 json 编码数据中,请提供帮助
谢谢
尝试在 httpPost.setEntity(new UrlEncodedFormEntity(params));
之后添加以下内容
httpPost.setHeader("Accept", "application/json");
正如 amendezcabrera 在评论中所说,
mysql_connect()
已弃用
所以我使用了 mysqli_connect()
,这导致我的 php 代码出现了一些其他错误,我已经修复了这些错误,现在可以正常工作了
事实证明,其他数据发送的是我想要的 json 编码数据
包含 php 条错误消息,因此我修复了它们
amendezcabrera 感谢您的帮助
我是 android 和 PHP 的初学者 我正在尝试将我的 android 应用程序连接到 Wamp 数据库服务器
我正在这里学习这门课程 http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
想法是使用 PHP 代码执行基本 SQL 操作
我有 activity 需要产品名称、价格和描述 并将其存储在数据库中,返回带有信息的 JSON 编码数据 关于插入成功与否
但是我在尝试从中创建 JSON对象时遇到错误
这就是我尝试过的
Log.e("JSON",json);
我使用日志查看数据是什么,这是我得到的
05-26 15:25:56.164 7801-7886/products.android.com.connectingproducts E/JSON: <br />
<font size='1'><table class='xdebug-error xe-deprecated' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
<tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp64\www\android_connect\db_connect.php on line <i>28</i></th></tr>
<tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
<tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
<tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0007</td><td bgcolor='#eeeeec' align='right'>241312</td><td bgcolor='#eeeeec'>{main}( )</td><td title='C:\wamp64\www\android_connect\create_product.php' bgcolor='#eeeeec'>...\create_product.php<b>:</b>0</td></tr>
<tr><td bgcolor='#eeeeec' align='center'>2</td><td bgcolor='#eeeeec' align='center'>0.0012</td><td bgcolor='#eeeeec' align='right'>252032</td><td bgcolor='#eeeeec'>DB_CONNECT->__construct( )</td><td title='C:\wamp64\www\android_connect\create_product.php' bgcolor='#eeeeec'>...\create_product.php<b>:</b>22</td></tr>
<tr><td bgcolor='#eeeeec' align='center'>3</td><td bgcolor='#eeeeec' align='center'>0.0012</td><td bgcolor='#eeeeec' align='right'>252120</td><td bgcolor='#eeeeec'>DB_CONNECT->connect( )</td><td title='C:\wamp64\www\android_connect\db_connect.php' bgcolor='#eeeeec'>...\db_connect.php<b>:</b>11</td></tr>
<tr><td bgcolor='#eeeeec' align='center'>4</td><td bgcolor='#eeeeec' align='center'>0.0016</td><td bgcolor='#eeeeec' align='right'>252936</td><td bgcolor='#eeeeec'><a href='http://www.php.net/function.mysql-connect' target='_new'>mysql_connect</a>
( )</td><td title='C:\wamp64\www\android_connect\db_connect.php' bgcolor='#eeeeec'>...\db_connect.php<b>:</b>28</td></tr>
</table></font>
{"success":1,"message":"Product successfully created."}
得到的数据似乎有一些 html 风格的代码,最后它有我想要的消息:
{"success":1,"message":"Product successfully created."}
所以这是我的JSON解析器代码
package products.android.com.connectingproducts;
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;
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.equals("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.equals("GET")){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
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());
}
Log.e("JSON",json);
// 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;
}
}
这是我的 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);
}
?>
如果您知道为什么将此数据添加到 json 编码数据中,请提供帮助
谢谢
尝试在 httpPost.setEntity(new UrlEncodedFormEntity(params));
之后添加以下内容httpPost.setHeader("Accept", "application/json");
正如 amendezcabrera 在评论中所说,
mysql_connect()
已弃用
所以我使用了 mysqli_connect()
,这导致我的 php 代码出现了一些其他错误,我已经修复了这些错误,现在可以正常工作了
事实证明,其他数据发送的是我想要的 json 编码数据 包含 php 条错误消息,因此我修复了它们
amendezcabrera 感谢您的帮助