用PHP服务器接收来自Android应用的数据。

3

我是新手,想要定期从一个安卓应用程序中获取一些数据。但是不知怎么的它不工作了。我已经写了一个PHP脚本,我需要添加更多的东西吗?

在AndroidManifest中需要添加权限吗?同时提供我的安卓应用程序代码,当我点击获取位置时,它会强制关闭。

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

}

我还想从LocationService类获取纬度和经度值到Post类中,Post类的代码是否正确呢?请帮助我。


你是否通过浏览器发送测试表单数据以查看PHP是否输出错误? - John Conde
看起来对我来说你已经有了所有必要的部件。 - John Conde
@JohnConde,你能帮我解决一个问题吗?我想从LocationService获取经纬度的值并传递到Post类中,不知道这样做是否正确? - Richard Rose
我是唯一一个看到代码中存在的严重安全漏洞吗?说真的,这里的SQL注入太简单了。 - Madara's Ghost
@RichardRose:请停止使用古老的mysql_*函数编写新代码。它们已经不再维护,社区已经开始弃用过程。相反,您应该学习有关准备语句的知识,并使用PDOMySQLi。如果您想学习,这里有一个非常好的与PDO相关的教程。此外,请勿直接在查询中使用$_POST变量而没有任何转义方式。 - Madara's Ghost
显示剩余3条评论
4个回答

3

正如 @Vivek Kumar Srivastava 所说的。

当您使用 postData 时,您发送的是 Json 格式,因此在 php 端,您需要实际解码它...

代码应该像这样。

在您的 Android 代码中创建一个 JSON 对象可能会更好,如下所示...

正如 Vivek Kumar Srivastava 所说:

当您使用 postData 时,您发送的是 Json 格式,因此在 php 端,您需要实际解码它。

在您的 Android 代码中创建一个 JSON 对象可能会更好,如下所示。

private postData() throws JSONException{  
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http://.../serverFile.php");
JSONObject json = new JSONObject();

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

    JSONArray postjson=new JSONArray();
    postjson.put(json);
    post.setHeader("json",json.toString());
    post.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
        }
    }

现在您的PHP代码...
$json = $_SERVER['HTTP_JSON'];//get the post you sent...
$data = json_decode($json); //decode the json formatted string...
$longitude = $data->longitude;
$latitude = $data->latitude;
$service = $data->service;
$devid = $data->devid;

然后继续使用您的SQL语句。如果要将它们读回Android,请按上面的代码将它们编码为JSON...


你好,感谢回复。那么我只需要将您提供的 PHP 部分和 Java 部分添加到 Post.java 中,对吗? - Richard Rose
我刚刚浏览了你的个人资料。你想做的是从你的应用程序中获取经纬度并将其发布到一个 PHP 网站上。你能帮我做这个吗?谢谢。 - Richard Rose
如果您正在使用Eclipse,只需右键单击下划线红色文本,它将自动添加它们。但如果没有,请检查我的答案,我刚刚进行了编辑。 - Abdullah Rasheed
我尝试了一下...但是它显示了一些有趣的错误...你能把你发布经纬度到Web服务器的代码发给我吗?在“post”这个词上给我显示错误... - Richard Rose
嘿,我在 PHP 脚本和 Java 文件中进行了更改... 网站上没有任何内容被发布... 请帮忙!!! - Richard Rose
显示剩余3条评论

1

你的 PHP 代码存在问题,因为 Android 端发送的数据是以 JSON 格式发送的,例如:

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

但是你直接尝试获取未解码的JSON数据。

因此,需要先解码JSON,然后按特定顺序获取数据

请参阅以下链接以了解更多详细信息

http://php.net/manual/en/function.json-decode.php


你是否已经通过给定的链接了解了? - Vivek Kumar Srivastava
@inspired的回答对您也有帮助,请仔细阅读。 - Vivek Kumar Srivastava

1
我建议您编写一个简单的脚本,以确保您确实正确地访问了数据库。您可以在浏览器中运行该脚本,从而排除与数据库的任何连接/访问问题:
<?php
mysql_connect("localhost","user","pass");
mysql_select_db("dbName");
$sql=mysql_query("select * from TABLENAME where COLUMNNAME like 'searchparameter'");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>

0

我没有看到任何 PHP 代码来接受 POST 数据。我写过类似的应用程序,其中我将数据发送到服务器并记录到数据库中。通常我会有一些脚本来接受 POST 数据并使用其中的值。您必须在 Android SDK 中使用 POST 方法将数据发送到 URL。这比使用 JSON 发送数据然后在 PHP 端解码要容易得多。如果我需要从服务器接收数据,则返回值为 JSON,然后在 Android 中使用 SDK 解码。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接