【问题标题】:PHP server to receive data from android applicationPHP服务器从android应用程序接收数据
【发布时间】:2012-05-05 17:10:55
【问题描述】:

我是通信方面的新手。只是试图定期从 android 应用程序中获取一些数据。但不知何故它不工作.. 写了一个 php 脚本我需要添加更多的东西..? 我是否需要在 androidmanifest 中添加任何权限..? 还提供了我的 android 应用程序代码。当我单击获取我的位置时,它会强制关闭。

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是否输出错误?
  • 没有..但是php服务器接收数据的代码是否完整..?
  • 看起来你已经拥有了我所有的必要部分。
  • @JohnConde 你能帮我解决我从 LocationService 到 Post 类的纬度和经度值的部分吗...如果正确与否..?
  • 您的 PHP 看起来是正确的。您的下一步应该是向该脚本发送模拟表单提交,看看会发生什么。如果有错误,您很有可能会看到它。

标签: php android json


【解决方案1】:

就像@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;

And then continue with your sql from there on. 如果您想将它们读回 Android,您可以将它们编码为 JSON,如上面的代码所示...

【讨论】:

  • 您好,谢谢您的回复.. 所以我只需要在我的代码中添加这个..?你给的 PHP 部分和 Post.java 的 java 部分..?
  • 我刚刚浏览了您的个人资料。您要做的是将您从应用程序中获得的经纬度发布到 php 的网站上。你能帮我解决这个问题吗...拜托
  • 所以我将在 php 中添加你给我的代码和 android 的代码..?你给了..?
  • :嘿,我试过你的代码......它告诉我把json.put("longitude", longitude); json.put("latitude", latitude); json.put("service", service); json.put("devid", devid);放在一个try catch......?你能把你的android代码部分寄给我吗..如果你不介意..
  • 如果您使用的是eclipse,如果您右键单击带下划线的红色文本,它将自动添加它们,但如果不检查我的答案,我只是编辑了
【解决方案2】:

我建议您编写一个简单的脚本来确保您确实可以正确访问数据库。您可以只在浏览器中运行脚本,这样就可以排除对数据库的任何连接/访问问题:

<?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();
?>

【讨论】:

    【解决方案3】:

    您的 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

    【讨论】:

    • 你是否通过给定的链接浏览
    • @inspired 的回答对你也有帮助,请仔细阅读
    【解决方案4】:

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

    【讨论】:

      猜你喜欢
      • 2021-05-08
      • 2012-08-17
      • 2017-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-19
      • 1970-01-01
      • 2021-07-30
      相关资源
      最近更新 更多