douer9399 2015-09-04 12:42
浏览 82
已采纳

当Android应用程序调用php文件时使用$ _POST

I'm trying to upload some data in the database with an android app. Until now everything was working fine, but now I need to add another column, so I modified the code and now it looks like the data sent by the phone is not readable by my php files. The important part of the code of my app is the following:

private static void post(String endpoint, Map<String, String> params)
        throws IOException {

    URL url;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=')
                .append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    Log.v(TAG, "Posting '" + body + "' to " + url);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        Log.e("URL", "> " + url);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        //conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded;charset=UTF-8");
        // post the request
        OutputStream out = conn.getOutputStream();
        Log.v(TAG, "Has posted" + bytes);
        out.write(bytes);
        out.close();
        // handle the response
        int status = conn.getResponseCode();
        if (status != 200) {
            Log.v(TAG, "Post Failed");
            throw new IOException("Post failed with error code " + status);
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

On the Logcat it looks like the app has been able to post the code effectively in byte format:

V/Alvaro Lloret GCM﹕ Posting email=llor&name=hola&arduinoweb=jaj&regId=APA' to http://youdomotics.com/mysecurity1/register.php
E/URL﹕ > http://website.com/mysecurity1/register.php
V/RenderScript﹕ Application requested CPU execution
V/RenderScript﹕ 0xaec16400 Launching thread(s), CPUs 4
V/Alvaro Lloret GCM﹕ Has posted[B@16d173b0
V/GCMRegistrar﹕ Setting registeredOnServer status as true until 2015-09-11 20:21:30.364
V/GCMBaseIntentService﹕ Releasing wakelock

Then, the code to receive the post with php is the following:

<?php
// response json
$json = array();

if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["regId"]) ) { 
     require("config.php");
    $con = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
    $name = $_POST["name"];
    $email = $_POST["email"];
    $arduinoweb = $_POST["arduinoweb"];
    $gcm_regid = $_POST["regId"]; // GCM Registration ID
    include_once './gcm.php';
    $query = "INSERT INTO gcm_users_new(name, email, gcm_regid, arduinoweb, created_at) VALUES('$name', '$email', '$gcm_regid', '$arduinoweb', NOW())";
    mysqli_query($con, $query);
} else {
    // user details missing
}

?>

This code worked perfectly without the new parameter arduinoweb, but since I added this other parameter, the row is not added into the database. If I comment the condition if (isset...), then the file adds a row in the table, but it's empty...

Any ideas?

Thank you!!

  • 写回答

1条回答 默认 最新

  • dongliuzhuan1219 2015-09-05 10:59
    关注

    Okay I solved!

    The perfect answer is here

    I just had to change to www. when I called the URL and that made it work!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 pip2.40更新pip2.43时报错
  • ¥15 换yum源但仍然用不了httpd
  • ¥50 C# 使用DEVMOD设置打印机首选项
  • ¥15 麒麟V10 arm安装gdal
  • ¥15 想用@vueuse 把项目动态改成深色主题,localStorge里面的vueuse-color-scheme一开始就给我改成了dark,不知道什么原因(相关搜索:背景颜色)
  • ¥20 OPENVPN连接问题
  • ¥15 flask实现搜索框访问数据库
  • ¥15 mrk3399刷完安卓11后投屏调试只能显示一个设备
  • ¥100 如何用js写一个游戏云存档
  • ¥15 ansys fluent计算闪退