【问题标题】:Sending a response from PHP to an Android/Java mobile app?从 PHP 向 Android/Java 移动应用程序发送响应?
【发布时间】:2011-06-05 04:44:12
【问题描述】:

我目前在我的 Android 应用程序中有一段代码用于获取设备 IMEI 并将该 IMEI 作为参数发送到托管在 Internet 上的 PHP 脚本。

PHP 脚本然后获取 IMEI 参数并检查文件以查看文件中是否存在 IMEI,如果存在,我希望能够让我的 Android 应用程序知道 IMEI 存在。所以基本上我只是希望能够将 True 返回到我的应用程序。

这可以使用 PHP 实现吗?

到目前为止,这是我的代码:

Android/Java

//Test HTTP Get for PHP

        public void executeHttpGet() throws Exception {
            BufferedReader in = null;
            try {
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet();
                request.setURI(new URI("http://testsite.com/" +
                        "imei_script.php?imei=" + telManager.getDeviceId()
                        ));
                HttpResponse response = client.execute(request);
                in = new BufferedReader
                (new InputStreamReader(response.getEntity().getContent()));
                StringBuffer sb = new StringBuffer("");
                String line = "";
                String NL = System.getProperty("line.separator");
                while ((line = in.readLine()) != null) {
                    sb.append(line + NL);
                }
                in.close();
                String page = sb.toString();
                System.out.println(page);
                } finally {
                if (in != null) {
                    try {
                        in.close();
                        } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

上面将 IMEI 作为参数发送到 PHP 脚本,该脚本成功提取并成功检查文件,但是如果 IMEI 匹配,我需要能够从 PHP 脚本返回肯定响应一个在文件中。

这里是 PHP:

<?php
    // to return plain text
    header("Content-Type: plain/text"); 
    $imei = $_GET["imei"];

    $file=fopen("imei.txt","r") or exit("Unable to open file!");

    while(!feof($file))
     {
    if ($imei==chop(fgets($file)))
     echo "True";
     }

    fclose($file);

?>

因此,我希望能够让我的应用程序知道找到了 IMEI,而不是 echo True,这可能吗?如果可以,我应该使用什么来实现它?

【问题讨论】:

    标签: java php android


    【解决方案1】:

    这是个好东西!事实上,你就快到了。你的 php 不应该改变,你的 java 应该!你只需要检查你的java代码中的响应结果。将您的 java 方法重新声明为

    public String executeHttpGet() {
    

    那么,让这个方法返回变量page。

    现在您可以在某处创建辅助方法。如果你把它和executeHttpGet放在同一个类中,它会是这样的:

    public boolean imeiIsKnown(){
        return executeHttpGet().equals("True");
    }
    

    现在你可以调用这个方法来确定你的imei是否在你的php后端中是已知的。

    【讨论】:

    • 嗯...也许imeiIsKnown方法应该返回executeHttpGet().startsWith("True");或者可能返回 executeHttpGet().equals("True" + System.getProperty("line.separator"));
    • 谢谢 我只是删除了新的行变量,以便在变量页面中只返回“True”,谢谢。现在开始研究将其连接到数据库:)
    • 假设在上述场景中询问我在 php 端并且 android 设备正在与我连接并采取一些响应。现在有什么方法可以确保响应已到达 android 应用程序。
    • 假设在上述场景中询问我在 php 端并且 android 设备正在与我连接并采取一些响应。现在有什么方法可以确保响应已到达 android 应用程序。 @davogotland
    【解决方案2】:

    我不确定它是否适合您 - 但您可以使用标题。如果找到 IMEI,您可以发送 header("Status: HTTP/1.1 200 OK") 否则发送 header("Status: 404 Not Found")。

    然后您应该检查应用程序中的响应状态。

    【讨论】:

      【解决方案3】:

      您的代码基本上是正确的,您需要做的就是稍微调整一下。我混合并匹配了上面的答案,因为我需要完全完成你想要做的事情。我创建了一个数据库,而不是检查 txt 文件。

      CREATE TABLE IF NOT EXISTS `user_device` (
        `Id_User_Device` int(11) NOT NULL auto_increment,
        `Nr_User_Device` varchar(60) collate utf8_bin NOT NULL,
        `Ic_User_Device_Satus` int(11) NOT NULL default '1',
        PRIMARY KEY  (`Id_User_Device`),
        KEY `Nr_User_Device` (`Nr_User_Device`,`Ic_User_Device_Satus`)
      ) 
      ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=20 ;
      

      java android 代码将是(不要忘记在 main.xml 布局文件中创建适当的调整,将 2 个元素插入经典的 helloworld 屏幕:

      import java.io.BufferedReader;
      import java.io.InputStreamReader;
      import java.net.URI;
      import org.apache.http.HttpResponse;
      import org.apache.http.client.HttpClient;
      import org.apache.http.client.methods.HttpGet;
      import org.apache.http.impl.client.DefaultHttpClient;
      import android.app.Activity;
      import android.os.Bundle;
      import android.util.Log;
      import android.widget.TextView;
      
      public class ZdeltestEMEIActivity extends Activity {
          /** Called when the activity is first created. */
          @Override
          public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
      
              DeviceUuidFactory deviceUuidFactory = new DeviceUuidFactory(this);
              String deviceUuid = deviceUuidFactory.getDeviceUuid().toString();
              Log.d("tgpost",deviceUuid);
              try {
                  String webPostAnswer = deviceIdCheck(deviceUuid);
                  if (webPostAnswer != null) {
                      TextView tv1 = (TextView) findViewById(R.id.textdisplay01);
                      TextView tv2 = (TextView) findViewById(R.id.textdisplay02);
                      tv1.setText(webPostAnswer);
                      tv2.setText(deviceUuid);
                      Log.d("tgpost", "okok "+webPostAnswer);
                  } else {
                      Log.d("tgpost", "nono empty");
                  }
              } catch (Exception e) {
                  // TODO Auto-generated catch block
                  Log.i("tgpost", "exc  " + e.getMessage());
                  Log.i("tgpost", e.toString());
                  Log.e("tgpost", e.getStackTrace().toString());
                  e.printStackTrace();
              }        
          }
          public String deviceIdCheck(String deviceUuidIn) throws Exception {
              boolean flagOK = false;
              BufferedReader in = null;
              try {
                  HttpClient client = new DefaultHttpClient();
                  HttpGet request = new HttpGet();
                  Log.v("tgpost", "okok");
                  //"imei_script.php?deviceId="; + telManager.getDeviceId()
                  request.setURI(new URI("http://www.you.net/" +
                          "deviceIdCheck.php?deviceId=" + deviceUuidIn
                          ));
                  HttpResponse response = client.execute(request);
                  Log.d("tgpost", "php answered> "+response);
                  in = new BufferedReader
                  (new InputStreamReader(response.getEntity().getContent()));
                  StringBuffer sb = new StringBuffer("");
                  String line = "";
                  String NL = System.getProperty("line.separator");
                  while ((line = in.readLine()) != null) {
                      sb.append(line + NL);
                  }
                  in.close();
                  String page = sb.toString();
                  Log.d("tgpost", "php answered HUMAN> "+page);
                  return page;
      
              } catch (Exception e) {
                  return "problems with connection "+e.getMessage();
              }  
          }
      }
      

      有一个额外的类

      import android.content.Context;
      import android.content.SharedPreferences;
      import android.provider.Settings.Secure;
      import android.telephony.TelephonyManager;
      import java.io.UnsupportedEncodingException;
      import java.util.UUID;
      
      public class DeviceUuidFactory {
          protected static final String PREFS_FILE = "device_id.xml";
          protected static final String PREFS_DEVICE_ID = "device_id";    
          protected static UUID uuid;
          public DeviceUuidFactory(Context context) { 
              if( uuid ==null ) {
                  synchronized (DeviceUuidFactory.class) {
                      if( uuid == null) {
                          final SharedPreferences prefs = context.getSharedPreferences( PREFS_FILE, 0);
                          final String id = prefs.getString(PREFS_DEVICE_ID, null );
                          if (id != null) {
                              // Use the ids previously computed and stored in the prefs file
                              uuid = UUID.fromString(id);
                          } else {
                              final String androidId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
      
                              // Use the Android ID unless it's broken, in which case fallback on deviceId,
                              // unless it's not available, then fallback on a random number which we store
                              // to a prefs file
                              try {
                                  if (!"9774d56d682e549c".equals(androidId)) {
                                      uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));
                                  } else {
                                      final String deviceId = ((TelephonyManager) context.getSystemService( Context.TELEPHONY_SERVICE )).getDeviceId();
                                      uuid = deviceId!=null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")) : UUID.randomUUID();
                                  }
                              } catch (UnsupportedEncodingException e) {
                                  throw new RuntimeException(e);
                              }
      
                              // Write the value out to the prefs file
                              prefs.edit().putString(PREFS_DEVICE_ID, uuid.toString() ).commit();
      
                          }
      
                      }
                  }
              }
      
          }
      
      
          /**
           * Returns a unique UUID for the current android device.  As with all UUIDs, this unique ID is "very highly likely"
           * to be unique across all Android devices.  Much more so than ANDROID_ID is.
           *
           * The UUID is generated by using ANDROID_ID as the base key if appropriate, falling back on
           * TelephonyManager.getDeviceID() if ANDROID_ID is known to be incorrect, and finally falling back
           * on a random UUID that's persisted to SharedPreferences if getDeviceID() does not return a
           * usable value.
           *
           * In some rare circumstances, this ID may change.  In particular, if the device is factory reset a new device ID
           * may be generated.  In addition, if a user upgrades their phone from certain buggy implementations of Android 2.2
           * to a newer, non-buggy version of Android, the device ID may change.  Or, if a user uninstalls your app on
           * a device that has neither a proper Android ID nor a Device ID, this ID may change on reinstallation.
           *
           * Note that if the code falls back on using TelephonyManager.getDeviceId(), the resulting ID will NOT
           * change after a factory reset.  Something to be aware of.
           *
           * Works around a bug in Android 2.2 for many devices when using ANDROID_ID directly.
           *
           * @see http://code.google.com/p/android/issues/detail?id=10603
           *
           * @return a UUID that may be used to uniquely identify your device for most purposes.
           */
          public UUID getDeviceUuid() {
              return uuid;
          }
      }
      

      在 php 方面:

      <?php
      // to return plain text
      // header("Content-Type: plain/text"); 
      include('/home/public_html/ConnStrDB.php');
      $deviceId = $_GET["deviceId"];
      $sql = "SELECT Nr_User_Device FROM user_device WHERE Nr_User_Device = '".$deviceId."'";
      $result = mysql_query($sql);
      if ($result) {
          $row = mysql_fetch_array($result);
          if ($row[0]) {$deviceIdFile = $row[0];} else {$deviceIdFile = "device not found";}
      } else {
          $deviceIdFile = "no check was made, empty set";
      }
      echo $_GET["deviceId"]."  ".$deviceIdFile;
      ?>
      

      并且(这样您就不必手动插入数字(只需更改提交中的 php 文件名):

      <?php
      // to return plain text
      // header("Content-Type: plain/text"); 
      include('/home/public_html/ConnStrDB.php');
      $deviceId = $_GET["deviceId"];
      $sql = "SELECT Nr_User_Device, Ic_User_Device_Status FROM user_device WHERE Nr_User_Device = ".$deviceId;
      
      $sql = "INSERT INTO user_device (Nr_User_Device) VALUES ('".$deviceId."')";
      $result = mysql_query($sql);
      if ($result) {
          $deviceIdFile = "device inserted";
      } else {
          $deviceIdFile = "not inserted";
      }
      echo $_GET["deviceId"]."  ".$deviceIdFile;
      ?>
      

      如果成功,您的手机屏幕将显示3次imei(设备上的,php中接收的,数据库中检索的)。

      ConnStrDB.php 是一个包含与 MySQL 数据库的完整连接的文件。

      如果您回复长文本,android 应用程序将收到它,以及任何 php 警告的详细版本。如果您不需要 json,您可以通过 php echo 回答任何 xml。谢谢你的问题,非常有用!感谢您提供出色的答案!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-27
        • 2012-04-24
        • 1970-01-01
        • 1970-01-01
        • 2015-11-25
        • 2017-12-28
        • 1970-01-01
        相关资源
        最近更新 更多