【问题标题】:Posting gps coordinates on php server from android phone从android手机在php服务器上发布gps坐标
【发布时间】:2012-06-09 12:11:21
【问题描述】:

我正在尝试的是获取我当前的位置(坐标),并且我想将这些坐标发布到服务器上。我已经使用 WAMP 制作了一个服务器。我已经编写了 php 代码和 java 中的代码,但它在 POST 字中显示错误。请告诉我它是否正确或者我是否可以修改它!

PHP 代码

<?php
echo 'Hello, world!';
$json = $_GET['jsonpost'];//get the post you sent...
$data = json_decode($json); //decode the json formatted string...
print_r($data);
$id = $data->id;
$devid = $data->devid;
$latitude = $data->latitude;
$longitude = $data->longitude;
$service = $data->service;
$con = mysql_connect("","","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("a5234826_ul", $con);
$devid = $_POST['devid']; 
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
echo "devid" +$devid;
echo "latitude" + $latitude;
echo "longitude" + $longitude; 
$sql = "INSERT INTO  `a5234826_ul`.`locations` (
`id` ,
`devid` ,
`latitude` ,
`longitude` ,
`service`
)
VALUES (
NULL ,  '$devid',  '$latitude',  '$longitude', '$service'  
)";
if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
mysql_close($con);
echo json_encode($variable);

?>

已编辑 LocationService.java

    @Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

public int onStartCommand(Intent intent, int flags, int startId) {
    PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
    wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "lock");
    wl.acquire();
    context = this;
    final String who = intent.getStringExtra("who");
    final LocationManager locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    final LocationListener listener = new LocationListener(){

        // start location changed

        public void onLocationChanged(Location loc) {
            double latitude = loc.getLatitude();
            double longitude = loc.getLongitude();


            // Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://.../serverFile.php");
            JSONObject json = new JSONObject();


            TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
            String devid = telephonyManager.getDeviceId();

            String postData = "{\"request\":{\"type\":\"locationinfo\"},\"userinfo\":{\"latitude\":\""+latitude+"\",\"longitude\":\""+longitude+"\",\"devid\":\""+devid+"\"}}";




            try {  

                json.put("longitude", longitude);//place each of the strings as you did in postData method
                json.put("latitude", latitude);

                json.put("devid", devid);

                JSONArray postjson=new JSONArray();
                postjson.put(json);
                httppost.setHeader("json",json.toString());
                httppost.getParams().setParameter("jsonpost",postjson);     
                HttpResponse response = httpclient.execute(httppost);

                // for JSON retrieval:
                if(response != null)
                { 
                InputStream is = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
                }
                } catch (IOException e) {
                e.printStackTrace();
                } finally {
                try {
                is.close();
                } catch (IOException e) {
                e.printStackTrace();
                }
                }
                String jsonStr = sb.toString(); //take the string you built place in a string



                JSONObject rec = new JSONObject(jsonStr);
                String longitudecord = rec.getString("lon");
                    String latitudecord = rec.getString("lat");
                // ...
                }
                }catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }




            if (who.equals("me")){
                Intent i = new Intent(context.getPackageName()+".LocationReceived");
                i.putExtra("lat", String.valueOf(latitude));
                i.putExtra("longitude", String.valueOf(longitude));
                i.putExtra("accuracy", String.valueOf(loc.getAccuracy()));
                context.sendBroadcast(i);
                Notification notif = new Notification();
                NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
                notif.tickerText = "Location Found!";
                notif.icon = R.drawable.ic_launcher;
                notif.flags = Notification.FLAG_AUTO_CANCEL;
                notif.when = System.currentTimeMillis();
                Intent notificationIntent = new Intent(context, TestLocatorActivity.class);
                notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                notificationIntent.putExtra("lat", String.valueOf(latitude));
                notificationIntent.putExtra("longitude", String.valueOf(longitude));
                notificationIntent.putExtra("accuracy", String.valueOf(loc.getAccuracy()));
                PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
                notif.setLatestEventInfo(context, "Location Found!", "Click to open.", contentIntent);
                nm.notify(0, notif);
            } else {
                SmsManager smsMan = SmsManager.getDefault();
                smsMan.sendTextMessage(who, null, "http://maps.google.com/maps?q=loc:"+latitude+","+longitude, null, null);
                smsMan.sendTextMessage(who, null, "Latitude: "+latitude+"\nLongitude: "+longitude, null, null);
            }
            locMan.removeUpdates(this);
            try {
                wl.release();
            } catch (Exception e){
                e.printStackTrace();
            }
            stopSelf();
        }

        public void onProviderDisabled(String provider){


        }

        public void onProviderEnabled(String provider) {
            //Log.i(tag, "GPS IS ON");
        }

        public void onStatusChanged(String provider, int status, Bundle extras){
            switch(status) {
                case LocationProvider.OUT_OF_SERVICE:
                case LocationProvider.TEMPORARILY_UNAVAILABLE:
                case LocationProvider.AVAILABLE:
                    break;
            }
        } };


    locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
    locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);

    return 2;
}

}

【问题讨论】:

  • POST 一词出现错误...
  • @shadyyx 请看编辑的部分...?还好吗..?
  • 我无法运行你的安卓代码,所以我不能说它是否正常...你的错误信息到底是什么?
  • 我试过...代码..但应用程序被强制关闭...
  • 编辑了我的答案,请阅读,想想你在做什么,并尝试使用google.com ...

标签: php android post gps


【解决方案1】:

我在这里看到的主要问题是你在谈论POST,但在你的android中LocationService你正在创建一个HttpGet对象:

HttpGet httppost = new HttpGet("http://.../serverFile.php");

然后不知从何而来,httpost 变量被用作post

post.setHeader("json",json.toString());
post.getParams().setParameter("jsonpost",postjson);

在 PHP 中,我不确定你想通过这个实现什么:

$_SERVER['HTTP_JSON'];

因为我确定没有这样的索引。而是调用

$_POST['jsonpost']; // <-- that is the parameter name from Your JAVA code...

$_GET['jsonpost']; // <-- that is the parameter name from Your JAVA code...

看起来你在此处复制 + 粘贴类似问题的代码(这应该是重复的!):Sending Data From Android To Server with JSON data

编辑: 好的,假设您的 android JAVA 代码正常并且您正在通过 GET 发送数据。然后你将不得不修复你的 PHP - 试试这个:

<?php
echo 'Hello, world!';

$json = $_GET['jsonpost']; // get the json you sent through GET...
$data = json_decode($json); // decode the json formatted string...

print_r($data); // print out the $data variable to see whether everything is OK...

$devid = $data->devid;
$longitude = $data->longitude;
$latitude = $data->latitude;

$con = mysql_connect("","","") or die('Could not connect: ' . mysql_error());    
mysql_select_db("a5234826_ul", $con);

echo "devid" +$devid;
echo "latitude" + $latitude;
echo "longitude" + $longitude; 

$sql = "INSERT INTO  `a5234826_ul`.`locations` (
    `devid`,
    `latitude`,
    `longitude` 
) VALUES (
    '$Devid',
    '$latitude',  
    '$longitude'
);";
if (!mysql_query($sql,$con)) {
    die('Error: ' . mysql_error());
}

mysql_close($con);
echo json_encode($variable);

您应该继续使用print_r($data); 并查看数据是否到达以及 JSON 是否已解码以及它包含哪些属性。

编辑 2 由于发布了 logcat: 您是否从 logcat 中读取了错误?太清楚了!!!程序员当然应该理解错误消息在说什么,并且应该了解他在做什么,而不仅仅是从某个地方复制+粘贴代码片段而不考虑它......在你的 manifest.xml 你需要添加一个权限 READ_PHONE_STATE -在此处阅读有关权限:http://developer.android.com/reference/android/Manifest.permission.html 以及在此处向 manifest.xml 添加权限:http://developer.android.com/guide/topics/security/security.html#permissions

【讨论】:

  • 没有从那里复制粘贴它..我该怎么办..你能帮我吗...拜托。
  • 嘿,我编辑了一些东西...一切正常...但是坐标和设备 ID 没有发布...
  • 好的,然后尝试谷歌这个词:android post data direct link。首先使用谷歌,当没有找到解决方案时,请在此处询问...
  • 我知道这篇旧文章,但有人应该注意,上面的 PHP 代码容易受到 SQL 注入的影响,这是一个相当大的安全问题。见stackoverflow.com/questions/60174/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-22
相关资源
最近更新 更多