0

I am aware that there has been a lot of questions regarding this but I'm confused and unable to find a solution for my problem.

I have a web service in php which read data from mysql server. The following code is the web-service script.

<?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); 
  ?>

This gives me the following output in the web-browser with this "http://localhost/test.php" {"name":"taz","country":"aus"}{"name":"fufu","country":"tutu"}{"name":"chikaka","country":"aceVentura"}

I have the following class in my android application. Very simple class but it returns an exception error on the HttpResponse execution.

 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();
     }
  }

This method is called in the mainActivity class to output the response. Could you give me some ideas what I'm doing wrong.

4

2 回答 2

0

确保在读取 InputStream 之前先读取响应状态

int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        return entity.getContent();
    }
}
于 2012-12-18T12:43:51.960 回答
0

对不起,我已经找到了解决方案。我真是太愚蠢了。我移动了位置,并没有意识到服务器地址发生了变化。

不过还是谢谢你的帮助

于 2012-12-19T00:26:16.430 回答