从php localhost获取数据

时间:2014-03-16 13:44:18

标签: android

我试图将我的android-login连接到php-localhost以便使用web服务器数据库(mysql),但由于我的代码错误,我无法做到这一点。
你能帮我解决这个问题..谢谢! Android:

   ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
   nameValuePairs.add(new BasicNameValuePair("username",username));
   nameValuePairs.add(new BasicNameValuePair("password",password));
   HttpClient httpclient = new DefaultHttpClient();
   HttpPost httppost = new HttpPost("http://localhost/folder/jsonlogin.php");  
   httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
   HttpResponse response = httpclient.execute(httppost);
   HttpEntity entity = response.getEntity();
   is = entity.getContent();

jsonlogin.php:

<?php
include('dbconnection.php');
$q=mysql_query("SELECT * FROM accounts WHERE username='".$_REQUEST['username']."' and password='".$_REQUEST['password']."'")or die(mysql_error());
$numrows = mysql_num_rows($q);
if($numrows > 0)
   {
    while($e=mysql_fetch_assoc($q))
        $output[]=$e;

print(json_encode($output));
   }  

错误日志:

enter image description here

2 个答案:

答案 0 :(得分:1)

HttpPost httppost = new HttpPost("localhost/folder/jsonlogin.php");  

这是罪魁祸首。您未指定协议,必须以http://开头,因此您的URL应如下所示:

HttpPost httppost = new HttpPost("http://localhost/folder/jsonlogin.php");  

但是,如果您在运行Android代码的其他计算机上调用此功能,则必须指定本地IP地址,例如:http://192.168.X.YYY/folder/jsonlogin.php

答案 1 :(得分:1)

如果您使用模拟器运行,则应使用 10.0.2.2 而不是 localhost

HttpPost httppost = new HttpPost("http://10.0.2.2/folder/jsonlogin.php");