【发布时间】:2016-02-22 00:27:55
【问题描述】:
我目前正在为一个小项目开发一个 Android 应用程序,该项目包括在 Android 平台上学习开发。我已经完成了所有应用程序,现在我需要将数据从应用程序发送到带有 MySQL 数据库的 PHP 服务器。我有一个 Web 服务,可以将通过 json 格式发送的数据插入数据库。我已经使用 Advanced Rest Client 测试了 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()的结果,看看这个:github.com/dmnugent80/ShareAppServerSide/blob/master/… -
感谢您的建议。我做到了,它非常有用。现在我有了一些进步,我插入但插入的对象中没有值。
-
我已经打印了我在网络服务中收到的 json,它是空的。所以,问题在于我将 json 发送到 Web 服务的方式。还有另一种使用 outputstreamwriter 的方法吗?因为我检查了 Logcat 上的 json,它的创建和格式都很好。
-
问题解决了!它完全来自我使用的免费服务器...buyethost...我已经在本地 wamp 服务器上对其进行了测试,并且可以正常工作!
标签: php android json web-services urlconnection