我知道有很多关于此的问题,但我很困惑,无法为我的问题找到解决方案。
我在php中有一个从mysql服务器读取数据的Web服务。以下代码是Web服务脚本。
<?php
$username = "XXXXX";
$password = "XXXXX";
$hostname = "localhost";
$response=array();
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("test",$dbhandle)
or die("Could not select test");
//execute the SQL query and return records
$result = mysql_query("SELECT name, country FROM android");
$response["infos"] = array();
while ($row = mysql_fetch_assoc($result)) {
$info = array();
$info["name"]=$row["name"];
$info["country"]=$row["country"];
echo json_encode($info);
}
//close the connection
mysql_close($dbhandle);
?>
这在Web浏览器中给出了以下输出,其中包含“http://localhost/test.php” { “名”: “TAZ”, “国”: “AUS”} { “名”: “福福”, “国”: “蓬蓬裙”} { “名”: “chikaka”, “国”: “aceVentura” }
我的android应用程序中有以下类。非常简单的类,但它在HttpResponse执行时返回异常错误。
public static final String URL = "http://192.168.0.5//test.php";
public static String connect(){
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
HttpResponse response = httpClient.execute(httpGet);
String result = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
return result;
} catch (Exception e) {
return "Error: " + e.getMessage();
}
}
在mainActivity类中调用此方法以输出响应。你能告诉我一些我做错的想法吗?
谢谢
答案 0 :(得分:0)
确保在阅读InputStream之前先阅读响应状态
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
if (entity != null) {
return entity.getContent();
}
}
答案 1 :(得分:0)
对不起伙计们 我找到了解决方案。这对我来说非常愚蠢。我移动了位置,没有意识到服务器地址已更改。
尽管如此,谢谢你的帮助