我正在使用HttpURLConnection将JSONObject数据发布到我的PHP后端。但是,我的后端PHP无法接收任何数据并回显“一些问题”。我需要从前端发布数据,从MySQL数据库中提取数据。以下是我的Android代码和PHP代码。
Android代码。
try {
URL urls = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urls.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestMethod("POST");
JSONObject deviceToken = new JSONObject();
deviceToken.put("RegistrationID", getRegIDs);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(deviceToken.toString());
wr.flush();
StringBuilder sb = new StringBuilder();
int HttpResult = conn.getResponseCode();
if(HttpResult == HttpURLConnection.HTTP_OK){
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line = null;
while ((line = br.readLine()) != null){
sb.append(line + "\n");
}
DataString = sb.toString();
br.close();
}
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
PHP代码
<?php
require_once('config.php');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header('P3P: CP="CAO PSA OUR"');
header("Content-Type: application/json; charset=utf-8");
$DeviceToken = $_POST['RegistrationID'];
$ReceiverDataSQL = "SELECT * FROM xpouser WHERE (device_token = '$DeviceToken')";
$ReceiverDataResult = mysqli_query($conn, $ReceiverDataSQL);
$messages = mysqli_fetch_assoc($ReceiverDataResult);
$ReceiverID = $messages['OID'];
if(!empty($ReceiverID)){
$channel_query = "SELECT * FROM xpochannel WHERE ChannelName LIKE '%$ReceiverID%'";
$result = mysqli_query($conn, $channel_query);
$msg = array();
$string = null;
while($messages = mysqli_fetch_assoc($result)){
array_push($msg, $messages);
}
if (is_array($msg) || is_object($msg)){
foreach($msg as $message){
$OID = $message['OID'];
$lastText_query = "SELECT * FROM xpomessage WHERE Recipient = '$OID' ORDER BY OID DESC LIMIT 1";
$lastText_result = mysqli_query($conn, $lastText_query);
$row_lastText = mysqli_fetch_assoc($lastText_result);
$last_text = $row_lastText['Message'];
$array = array(
'ChannelName' => $message['ChannelName'],
'LastText' => $last_text);
$obj = json_encode($array);
$string .= $obj;
}
$returnObj = "[" .$string. "]";
$new_str = str_replace('}{', '},{ ', $returnObj);
echo $new_str;
}
}else{
echo "Some Problem";
}
?>