我有一个包含两列(id、名称)的数据库,位于 localhost:88。我试图从我的 android 应用程序进入它,但在解析 Json 时,应用程序给出了 JSONException。我试过在没有 Json 解析的情况下从 php 获取数据,只是一个字符串。但它只得到 NULL。 这是我的 PHP 脚本:
<?php
$con = mysqli_connect('127.0.0.1:3306', 'root', '', 'test');
if(mysqli_connect_errno())
echo 'Failed to connect to MySQL: ' . mysqli_connect_error();
$query = mysqli_query($con, "SELECT * FROM example");
$rows = array();
while($r = mysqli_fetch_assoc($query))
$rows[] = $r;
print(json_encode($rows));
mysqli_close($con);
?>
这是我的方法:
public class MainActivity extends Activity
{
TextView txt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
txt = (TextView) findViewById(R.id.textView);
txt.setText(getDataFromDB());
}
public String getDataFromDB()
{
try
{
HttpPost httpPost = new HttpPost("http://127.0.0.1:88/basicphp/GetData.php");
HttpClient httpClient = new DefaultHttpClient();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpClient.execute(httpPost, responseHandler);
return response.trim();
}
catch(Exception e){
return "error\n" + e.getMessage();
}
}
}
当我在浏览器中输入“http://localhost:88/basicphp/GetData.php
”时,我得到了这个:“[{"id":"1","name":“约翰”}]”。所以我想至少在我的 TextView 上得到这个字符串,但是 TextView 只得到 null:( 那么,我做错了什么?
最佳答案
改变
HttpPost httpPost = new HttpPost("http://127.0.0.1:88/basicphp/GetData.php");
它给
HttpPost httpPost = new HttpPost("http://10.0.2.2/basicphp/GetData.php");
访问【问题】:java.net.ConnectException: /127.0.0.1:8080 an android emulator
关于php - Android HttpPost 从 PHP 脚本而不是 JSONArray 获取 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25968437/