0
所以我見過很多教程來做Android的POST請求,我發現有這麼多的代碼,但沒有一個真正起作用,這讓我發瘋。POST請求根本不起作用android
該代碼看起來不錯,但我不知道Android是非常奇怪的。
這裏是Android的我POST請求:
thread = new Thread(new Runnable() {
@Override
public void run() {
try {
String data = URLEncoder.encode("pseudo","UTF-8")+"="+URLEncoder.encode(edit.getText().toString(),"UTF-8");
data += "&"+"score"+"="+URLEncoder.encode(String.valueOf(score),"UTF-8");
URL url = new URL("http://mywebsite/serveur.php?"+data);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
wr.write(data);
wr.flush();
wr.close();
os.close();
android.util.Log.d("my Tag",data);
connection.connect();
android.content.Intent Npage = new android.content.Intent(SubmiturScore.this, ListOscore.class);
startActivity(Npage);
} catch (IOException e) {
e.printStackTrace();
}
而在PHP服務器的代碼將數據存儲在MySQL數據庫:
<?php
$reponse = array();
$pseudo = urldecode($_POST['pseudo']);
$score = intval(urldecode($_POST['score']));
$mysqli = new MySQLi("myhost","myuser","mypassword","mydb");
$result = $mysqli->query("INSERT INTO SIDB (pseudo,score) VALUES('$pseudo',$score)");
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
if ($result) {
$response["success"] = 1;
$response["message"] = "SUCCESS!";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "FAILURE!";
echo json_encode($response);
} ?>
我已經發布了消息堆棧溢出,但我認爲該代碼將工作,但沒有...你能幫我!
嘗試將'HttpUrlConnection'更改爲'HttpsUrlConnection'。 –
你有什麼異常嗎? –
你得到了什麼錯誤?是在所有執行的PHP?你似乎沒有閱讀php腳本的json輸出。 – YvesLeBorg