使用httpclient从webservice中读取

时间:2011-08-09 14:44:17

标签: php android web-services json


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

$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”。 有人可以告诉我有什么问题吗?

1 个答案:

答案 0 :(得分:1)

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

如果没有别的,请尝试以下方法:

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

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