gpt4 book ai didi

php - 使用 POST 方法和 HttpURLConnection 将 JSON 对象从 Android 发送到 PHP 服务器

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:12:34 25 4
gpt4 key购买 nike

我正在尝试在我的 Android 应用程序和本地网络上的 WampServer 之间建立通信。

当我想从服务器读取数据时,我已经成功了,但是当我尝试向服务器发送数据时却遇到了问题。

我正在使用服务来建立通信:

public class SynchronisationService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);

new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL("http://192.168.37.23/happiness_barometer/php_input.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(false);
connection.setRequestMethod("POST");
connection.connect();
OutputStream outputStream = connection.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(outputStream);
JSONObject jsonObject = new JSONObject();
jsonObject.put("rate", 1);
writer.write(URLEncoder.encode(jsonObject.toString(), "UTF-8"));
writer.flush();
writer.close();

} catch (Exception e) {
Log.v("EXCEPTION", e.getMessage());
}
}
}).start();


stopSelf();

return flags;
}

还有我的 php 文件:

 <?php 

try
{
$bdd = new PDO('mysql:host=localhost;dbname=happiness_barometer;charset=utf8', 'utilisateur', '');
} catch (Exception $e)
{
die('Erreur : '.$e->getMessage());
}

$sql = $bdd->prepare(
'INSERT INTO rates (rate, comment, category, day, month, year, hour, minute, day_of_week, week, rate_number)
VALUES (:rate, :comment, :category, :day, :month, :year, :hour, :minute, :day_of_week, :week, :rate_number)');
if (!empty($_POST['rate'])) {
$sql->execute(array(
'rate' => $_POST['rate'],
'comment' => '',
'category' => 'pro',
'day' => 19,
'month' => 8,
'year' => 2015,
'hour' => 18,
'minute' => 3,
'day_of_week' =>3,
'week' => 33,
'rate_number' => 2));
}
?>

当我运行我的应用程序时,没有任何内容添加到我的数据库中。我认为 $_POST['rate'] 中没有任何内容。

请告诉我我的代码有什么问题?

最佳答案

最后,我成功地向我的服务器发送了一个 JSONObject。

我将此代码用于 android 部分:

new Thread(new Runnable() {
@Override
public void run() {
OutputStream os = null;
InputStream is = null;
HttpURLConnection conn = null;
try {
//constants
URL url = new URL("http://192.168.43.64/happiness_barometer/php_input.php");
JSONObject jsonObject = new JSONObject();
jsonObject.put("rate", "1");
jsonObject.put("comment", "OK");
jsonObject.put("category", "pro");
jsonObject.put("day", "19");
jsonObject.put("month", "8");
jsonObject.put("year", "2015");
jsonObject.put("hour", "16");
jsonObject.put("minute", "41");
jsonObject.put("day_of_week", "3");
jsonObject.put("week", "34");
jsonObject.put("rate_number", "1");
String message = jsonObject.toString();

conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout( 10000 /*milliseconds*/ );
conn.setConnectTimeout( 15000 /* milliseconds */ );
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(message.getBytes().length);

//make some HTTP header nicety
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");

//open
conn.connect();

//setup send
os = new BufferedOutputStream(conn.getOutputStream());
os.write(message.getBytes());
//clean up
os.flush();

//do somehting with response
is = conn.getInputStream();
//String contentAsString = readIt(is,len);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
//clean up
try {
os.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}

conn.disconnect();
}
}
}).start();

还有这个在 php 部分:

$json = file_get_contents('php://input');
$obj = json_decode($json);
$rate = $obj->{'rate'};
$comment = $obj->{'comment'};
$category = $obj->{'category'};
$day = $obj->{'day'};
$month = $obj->{'month'};
$year = $obj->{'year'};
$hour = $obj->{'hour'};
$minute = $obj->{'minute'};
$day_of_week = $obj->{'day_of_week'};
$week = $obj->{'week'};
$rate_number = $obj->{'rate_number'};

try
{
$bdd = new PDO('mysql:host=localhost;dbname=happiness_barometer;charset=utf8', 'utilisateur', '');
} catch (Exception $e)
{
die('Erreur : '.$e->getMessage());
}

$sql = $bdd->prepare(
'INSERT INTO rates (rate, comment, category, day, month, year, hour, minute, day_of_week, week, rate_number)
VALUES (:rate, :comment, :category, :day, :month, :year, :hour, :minute, :day_of_week, :week, :rate_number)');
if (!empty($rate)) {
$sql->execute(array(
'rate' => $rate,
'comment' => $comment,
'category' => $category,
'day' => $day,
'month' => $month,
'year' => $year,
'hour' => $hour,
'minute' => $minute,
'day_of_week' => $day_of_week,
'week' => $week,
'rate_number' => $rate_number));
}

希望对其他人有帮助;)

关于php - 使用 POST 方法和 HttpURLConnection 将 JSON 对象从 Android 发送到 PHP 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32114698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com