【问题标题】:Read from webservice using httpclient使用 httpclient 从 web 服务读取
【发布时间】:2011-08-09 14:44:16
【问题描述】:


我有一个应该从网络服务读取 mysql 数据库的 android 应用程序。
这是网络服务中的代码:

$q=mysql_query("SELECT * FROM Rates");
while($e=mysql_fetch_assoc($q))
       $output[]=$e;

print(json_encode($output));
mysql_close();

这是我的应用程序中的代码:

public void getQuery() {
    String result = "";
     InputStream is;
    try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet("http://dakatora.co.il/android/androidsql.php");
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
    }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
            is = new InputStream() {

                @Override
                public int read() throws IOException {
                    // TODO Auto-generated method stub
                    return 0;
                }
            };
    }
    try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
            }
            is.close();

            result=sb.toString();
    }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
    }

    //parse json data

由于某种原因,结果字符串没有得到查询,而是只得到“\n”。 谁能告诉我怎么了?

【问题讨论】:

    标签: php android web-services json


    【解决方案1】:

    您的 .php 页面没有输出任何内容。尝试在浏览器中点击 URL - 你会得到一个空白页面。如果您发布的 PHP 代码是整个文件,那么您忘记了实际连接到数据库。检查服务器的错误日志,看看脚本是否吐出任何错误(和/或打开 php 的 display_errors 选项)。

    如果没有其他问题,请尝试以下操作:

    $q = mysql_query("SELECT * FROM Rates") or die(mysql_error());
    

    假设查询会成功是一种糟糕的做法,即使是这样的微不足道的查询也是如此。 SQL 语法可能是完美的,但有太多其他原因导致事情出错而没有任何类型的错误处理。

    【讨论】:

    • 你是对的,我收到以下错误:致命错误:调用 /var/www/vhosts/dakatora.co.il/httpdocs/android/androidsql.php 中的未定义函数 json_encode()第 11 行我该怎么办?
    • 您可能使用的是较旧的 PHP 版本。 json_encode() 自 v5.2 起成为标准,因此您必须尝试旧的 PECL 包 (pecl.php.net/package/json),或升级到现代 PHP 版本。
    • 谢谢,我看看我能做什么(我只写java应用程序,web服务由我的同事维护)。
    • 所以,如果 Marc 是对的,为什么我会在他的回答中看到减号...... +1 以平衡力量
    • @necronet:有人进行了一次小小的投票。不知道为什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    相关资源
    最近更新 更多