【问题标题】:Android call PHP with HTTP-GETAndroid 使用 HTTP-GET 调用 PHP
【发布时间】:2013-03-10 13:49:59
【问题描述】:

我的问题是:如何使用 HttpPost 调用 php?

 final HttpClient httpclient = new DefaultHttpClient();
final HttpPost httppost = new HttpPost("www.example.de/mySkript.php");
final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("param1", "value1"));
nameValuePairs.add(new BasicNameValuePair("param2", "value2"));

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
final HttpResponse response = httpclient.execute(httppost);

我们发现了这个...但我们不想将参数/值发送到 PHP,因为如果您通过 URL 调用我们的 PHP 计数 +1。任何代码只调用PHP?

谢谢你:)

编辑: PHP 是:

<?php
$userdatei = fopen ("test.txt","r");
$zeile = fgets($userdatei, 500);
$zeile++;
fclose($userdatei);

$schreiben = fopen ("test.txt","w");
fwrite($schreiben, $zeile);
fclose($schreiben);
?>

并使用此代码:

    public static HttpResponse hitUrl(String url) {
      try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(new HttpGet(url));
        return response;
      } catch (Exception e) {
          e.printStackTrace();
        return null;
      }
    }

然后调用它:

hitUrl("http://example.de/test.php");

这样对吗?

【问题讨论】:

  • "counting +1"..你能进一步解释一下吗?为什么不制作另一个 PHP 脚本,例如“example.de/api.php”?
  • @redreggae 我们的 PHP 负责统计浏览量。因此,如果您访问 www.example.com/test.php,PHP 会在 TextFile 中写入查看次数。
  • 好的,但是你为什么不为 Android 创建另一个入口点,比如“example.de/api.php”,但它不算数?你不能在另一台机器的命令行上运行 PHP。
  • 所以我想要的只是调用这个 URL:www.example.com/test.php 但不在 WebView 中......如何做到这一点?
  • @redreggae 你的意思是什么:你不能在另一台机器的命令行上运行 PHP?

标签: php android http url http-post


【解决方案1】:

你需要向你的服务器发出 HTTP GET 请求,你可以使用类似的东西:

public static HttpResponse hitUrl(String url) {
  try {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(new HttpGet(url));
    return response;
  } catch (Exception e) {
    Log.("[GET REQUEST]", "Network exception", e);
    return null;
  }
}

我还可以为此服务器异步调用推荐 AQuery 库:

http://code.google.com/p/android-query/

【讨论】:

  • 检查响应对象,也许你调用了错误的 URL?或者你的 PHP 脚本崩溃了?尝试发布您的 PHP 代码。
  • 看起来不错。 HttpResponse 怎么样? http状态码是什么?当你在你的 PHP 代码中添加 echo 时,你能从 Android 上的响应中读取它的输出吗?
猜你喜欢
  • 2019-04-17
  • 2012-11-28
  • 1970-01-01
  • 1970-01-01
  • 2019-02-28
  • 2014-12-24
  • 2018-12-14
  • 1970-01-01
  • 2018-10-31
相关资源
最近更新 更多