我正在开发一款Android应用程序,这是一个学习在Android平台上开发的小项目。我已经完成了所有应用程序,现在需要通过PHP和MySQL数据库将数据从应用程序发送到服务器。我有一个Web服务,可以通过json格式的数据将其插入到数据库中。我已经使用高级REST客户端测试了Web服务,并成功将数据插入到我的数据库中。现在我正在从我的Android应用程序进行测试,但它无法正常工作。我已检查了连接状态,它是“OK”,但是当我检查数据库时,没有插入。以下是我的PHP Web服务:
<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);
$con = mysql_connect('host','login','password')
or die('Cannot connect to the DB');
mysql_select_db('database_name',$con);
mysql_query("INSERT INTO `commercial` (firstName, surNameC, email, number, salonName, uuid)
VALUES ('".$obj->{'firstname'}."','".$obj->{'name'}."','".$obj-> {'email'}."','".$obj->{'phonenumber'}."','".$obj->{'fairreference'}."','".$obj-> {'commercialuuid'}."')");
mysql_close($con);
$posts = "INSERTION OK";
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
?>
在 Android 端发送过程:
URL url;
HttpURLConnection urlConnection;
StringBuilder strBuilder;
try {
url = new URL(URL);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.connect();
JSONObject jsonObject = new JSONObject();
jsonObject.put("commercialuuid", args[0]);
jsonObject.put("name", args[1]);
jsonObject.put("firstname", args[2]);
jsonObject.put("phonenumber", args[3]);
jsonObject.put("email", args[4]);
jsonObject.put("fairreference", args[5]);
Log.d("json", jsonObject.toString());
Log.d("request", "starting");
OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream());
writer.write(jsonObject.toString());
writer.flush();
Log.e("connection status",urlConnection.getResponseMessage());
//get the response from the web service
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
strBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
strBuilder.append(line);
}
writer.close();
reader.close();
urlConnection.disconnect();
return null;
} catch (Exception e) {
e.printStackTrace();
}
我查阅了几个已验证的帖子并根据它们进行了工作,但我真的不明白为什么它不起作用。 如果有人能帮助我,我将非常感激。
谢谢。
mysql_query()
的结果,请查看此链接:https://github.com/dmnugent80/ShareAppServerSide/blob/master/databaseInsert.php - Daniel Nugent