标签:android style blog http io color ar os sp
一、首先是Android客户端解析PHP返回的JSON数据
1、PHP代码(这里用到了数据库,如果没有准备数据库的话,可以自定义字符串)
<?php $link=mysql_connect(SAE_MYSQL_HOST_M.‘:‘.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS); mysql_query("SET NAMES utf8"); mysql_select_db(SAE_MYSQL_DB,$link); $sql=mysql_query("select * from users ",$link); while($row=mysql_fetch_assoc($sql)) $output[]=$row; echo json_encode($output); mysql_close(); ?>
2、Android端代码(部分代码)
private Boolean checkuser(String url, String username, String password) { int res = 0; HttpClient client = new DefaultHttpClient(); StringBuilder str =new StringBuilder(); HttpGet httpget = new HttpGet(url); BufferedReader buffer = null; try { HttpResponse httpRes = client.execute(httpget); res = httpRes.getStatusLine().getStatusCode(); if(res == 200) { buffer = new BufferedReader(new InputStreamReader(httpRes.getEntity().getContent())); for(String s = buffer.readLine();s != null;s = buffer.readLine()) { str.append(s); } buffer.close(); JSONArray json = new JSONArray(str.toString()); String struser = ""; String strpass = ""; for(int i = 0;i < json.length();i++) { JSONObject jsonObject = (JSONObject)json.opt(i); struser = jsonObject.getString("username"); strpass = jsonObject.getString("password"); if(struser.equals(username)&&strpass.equals(password)) { return true; } } return false; } else { Log.v(null, "httperror"); return false; } }catch(Exception e) { e.printStackTrace(); return false; } }
这不是重点,重点在下面PHP解析Android发送的JSON数据
二、PHP解析Android发送的JSON数据
1、Android端代码(部分)
Boolean RegUser(String url,String regname, String regpass) { ArrayList<NameValuePair> arrayList = new ArrayList<NameValuePair>(); arrayList.add(new BasicNameValuePair("username", regname)); arrayList.add(new BasicNameValuePair("password",regpass)); try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); httppost.setEntity(new UrlEncodedFormEntity(arrayList)); HttpResponse httpres = httpclient.execute(httppost); return true; }catch(Exception e) { e.printStackTrace(); return false; } }
整个发送过程尤其重要!!!!!并且容易出错。
2、PHP端代码
<?php $name = $_REQUEST[‘username‘]; $pass = $_REQUEST[‘password‘]; $link=mysql_connect(SAE_MYSQL_HOST_M.‘:‘.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS); mysql_query("SET NAMES utf8"); mysql_select_db(SAE_MYSQL_DB,$link); $sql = "insert into users (username,password) values (‘$name‘,‘$pass‘)"; mysql_query($sql,$link); mysql_close($link); ?>
这里接收客户端JSON数据用的是REQUEST,和POST的区别不是很清楚。
总结:
1、找了一下午,最后发现问题应该是客户端发送数据不成功。
2、也有可能是我之前用的是POST接收。
3、代码出问题还是不要找我,虽然是我写的,但是它自己长歪了。
4、如果转载,请注明出处(by 不剃头的一休哥)。
标签:android style blog http io color ar os sp
原文地址:http://www.cnblogs.com/hearzeus/p/4102647.html