从PHP发送响应到Android/Java移动应用程序?

Don*_*rty 7 php java android

我目前在我的Android应用程序中有一段代码,它接收设备IMEI并将IMEI作为参数发送到Internet上托管的PHP脚本.

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

这可能使用PHP吗?

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

安卓/ 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();
                    }
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

上面将IMEI作为参数发送到PHP脚本,该脚本成功获取它并成功运行对文件的检查,但是我需要能够从PHP脚本发回肯定响应,如果IMEI匹配文件.

这是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);

?>
Run Code Online (Sandbox Code Playgroud)

因此,我希望能够让我的应用程序知道IMEI被发现,这是否可能,如果是这样,我应该用什么来实现它?

dav*_*and 3

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

public String executeHttpGet() {
Run Code Online (Sandbox Code Playgroud)

然后,让这个方法返回变量page。

现在您可以在某处创建一个辅助方法。如果你把它和executeHttpGet放在同一个类中,它将看起来像这样:

public boolean imeiIsKnown(){
    return executeHttpGet().equals("True");
}
Run Code Online (Sandbox Code Playgroud)

现在你可以调用这个方法来查明你的 IMEI 在你的 php 后端是否已知。