2017-05-08 119 views
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); 
} ?> 

我已經發布了消息堆棧溢出,但我認爲該代碼將工作,但沒有...你能幫我!

+0

嘗試將'HttpUrlConnection'更改爲'HttpsUrlConnection'。 –

+0

你有什麼異常嗎? –

+0

你得到了什麼錯誤?是在所有執行的PHP?你似乎沒有閱讀php腳本的json輸出。 – YvesLeBorg

回答

0

所以我不知道f ***發生在Android上的POST。爲了解決我的問題,我只是調用一個webview,將數據的URL收取所以PHP腳本可以恢復數據,並最終將其存儲在數據庫中...

這是艱難的,但我終於suceeded YES!

wb.getSettings().setJavaScriptEnabled(true); 
    wb.getSettings().setDomStorageEnabled(true); 
    wb.loadUrl("http://yourscript.php?"+data);