我目前正在爲一個小型項目開發一個Android應用程序,其中包括學習Android平臺上的開發。我已經做了所有的應用程序,現在我需要使用MySQL數據庫將應用程序中的數據發送到PHP中的服務器。我有一個Web服務,通過json格式發送數據,從而在數據庫中插入數據。我已經使用Advanced Rest Client測試了Web服務,並且成功地將數據插入到了我的數據庫中。現在我從我的Android應用程序應用程序進行測試,但它不起作用。我檢查了連接狀態,它是「OK」,但是當我檢查數據庫時,沒有插入。通過JSON從Android發送數據到PHP使用HttpUrlConnection的Web服務
下面是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()的結果,採取一個廁所k at this:https://github.com/dmnugent80/ShareAppServerSide/blob/master/databaseInsert.php –
感謝您的建議。我做到了,它非常有用。現在我有一些進步,我插入但插入的對象中沒有值。 –
我打印了我在Web服務中收到的json,它是空的。所以,問題是我發送json到web服務的方式。有另一種使用outputstreamwriter的方法嗎?因爲我在Logcat上檢查了json,並且很好地創建和格式化了它。 –