POST请求在所有android上都不起作用

时间:2017-05-08 18:14:21

标签: php android mysql post server

所以我在Android中看到很多教程要做POST请求,但我找到了很多代码,但是没有一个真正有用,这让我很疯狂。

代码看起来不错,但我不知道Android是非常奇怪的。

以下是Android中的帖子请求:

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);
} ?>

我已经在堆栈溢出中发布了一条消息,但我认为代码可以正常工作但是没有......你能帮帮我吗?

1 个答案:

答案 0 :(得分:0)

所以我不知道Android上的POST发生了什么。为了解决我的问题,我刚刚调用了一个webview,它将使用数据来收取URL,这样php脚本就可以恢复数据并最终将其存储在数据库中......

这很艰难,但我终于成功了!

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