我正在尝试创建一个通过php和JSON连接到mySQL数据库的android应用程序。 这是我在服务器上的php文件:
<?php
$host="my_host";
$username="my_name";
$password="my_password";
$db_name="my_db_name";
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "SELECT UserID, DisplayName
FROM User
WHERE (UserName LIKE '%it%') OR (DisplayName LIKE '%it%')";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['UserRes'][]=$row;
}
}
mysql_close($con);
echo json_encode($json);
?>
这是我的JSON java类代码:
public class JSONClass extends AsyncTask<String,Void,String>{
public HashMap<String, String> tbl = new HashMap<String, String>();
private Context context;
public JSONClass(Context context) {
this.context = context;
}
@Override
protected String doInBackground(String... arg0) {
try{
String link = "some url";
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
我是新手,只想从那里获得基础知识和工作。 php文件应该返回一行作为答案,但据我所知,该函数属于try-catch部分。我知道结果应该是HashMap。有人可以告诉我我做错了什么或给我一个提示,以获得结果?提前谢谢!
答案 0 :(得分:0)
这是您从url
获取数据的方式,其中url
下面是您的PHP脚本的网址:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
JSONArray ja = new JSONArray(result);
for(int i = 0 ; i < ja.length() ; i++){
String name = ja.getJSONObject(i).getString("name"); //write name of column
}