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!

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

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?