【发布时间】:2010-11-24 19:57:07
【问题描述】:
我有一个从远程数据库获取一些数据的应用程序。 我用PHP和下面的代码连接数据库。
mysql_connect($host,$username,$password) or die( "no connection");
@mysql_select_db($database) or die( "Unable to select database");
$query = $_REQUEST['query'];
$q=mysql_query($query);
while($e=mysql_fetch_assoc($q)) {
$output[]=$e;
}
print(json_encode($output));
mysql_close();
然后我通过以下 java 代码进行连接
public void connect(ArrayList<NameValuePair> nameValuePairs) {
result = "";
InputStream is = null;
String url = "http://'ipadress'/PhpProject1/EmptyPHP.php";
//Get the content
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("Connect", "Error in http connection " + e.toString());
}
//Convert content toString
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
//result = replaceString(sb.toString());
} catch (Exception e) {
Log.e("Connect", "Error converting result " + e.toString());
}
}
完成后我会通过以下方式进行查询
public void query(String query){
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("query", query));
connect(nameValuePairs);
}
虽然这对模拟器很有效,但在手机上使用时会出现问题。
有人知道这是为什么吗?
提前谢谢你
【问题讨论】:
-
请描述您遇到的问题。
-
我没有遇到任何异常。使用模拟器时会直接进行查询,但使用手机时会出现黑色显示。测试它我只有一个使用 setText(queryResult) 的 TextView 但手机上没有显示任何内容
-
打印以记录您在结果字段中获得的内容以及您在 php.ini 的响应中获得的内容。我会删除 8 作为 BufferedReader 构造函数的参数...
-
现在发现一个错误:ERROR Connect Error in http connection java.net.SocketException: The operation timed out
-
@Bastaix 你能导航到手机浏览器中的 URL 吗?