dtpn60029 2014-05-22 15:52
浏览 41
已采纳

将多个数据从Android发布到PHP Web服务

So far I can send one set of data from Android to PHP web service. I'm hoping to send an array, and have a for loop in the web service. Is that possible? Is that a good solution? In this project, I'm trying to sync SQLite with MySQL.

Here's my code

String username, userid;
    username = "Kate";
    userid = "3";
    String data = "";

    try {
        data = URLEncoder.encode("username", "UTF-8") + "="
                + URLEncoder.encode(username, "UTF-8");
        data += "&" + URLEncoder.encode("userid", "UTF-8") + "="
                + URLEncoder.encode(userid, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String text = "";
    BufferedReader reader = null;

    try {

        URL url = new URL(
                address);

        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(
                conn.getOutputStream());
        wr.write(data);
        wr.flush();

        // Get the response
        reader = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = reader.readLine()) != null) {
            sb.append(line + "
");
        }
        text = sb.toString();
    } catch (Exception ex) {

    } finally {
        try {
            reader.close();
        } catch (Exception ex) { }
    }

And this

<?php 
include '../inc/connect.php';
include '../inc/class/mysql.class.php'; 

$name   = urldecode($_POST['username']);
$user   = urldecode($_POST['userid']);

print " ==== POST DATA =====
Name  : $name
Email : $email
User  : $user
Pass  : $pass";

$ins = mysql_query("INSERT INTO users (UserName, FullName) VALUES ('$name','$user')") or die(mysql_error());
if ($ins) {
    echo json_encode(array("result"=>"success","result_txt"=>"Branch sucessfully added."));
    exit();
}
?>
  • 写回答

1条回答 默认 最新

  • drh78568 2014-05-22 16:01
    关注

    You could send the input as JSON and then get PHP to decode it.

    So you'd encode all your data in the android app and send it as one big encoded string, possibly using URI encoding or Base64, then in the PHP do:

    $data = json_decode($_POST['data']);
    

    If you use base64 then you'd do:

    $data = json_decode(base64_decode($_POST['data']));
    

    If you just send it as one string

    $data = json_decode(urldecode($_POST['data']));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?