In questo esempio è utilizzato l'oggetto JSON.
Richiesta di dati ad una JSP:
public ArrayList<Map<String,String>> selectNameSurname(){ ArrayList<Map<String,String>> listaDb = new ArrayList<Map<String,String>>(); InputStream is = null; StringBuilder sb=null; String result=null; try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://wwwwww/data.php");//link HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); }catch(Exception e){ //something here } //convert response to string try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); sb = new StringBuilder(); sb.append(reader.readLine() + "\n"); String line="0"; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result=sb.toString(); }catch(Exception e){ //something here } String name; String surname; JSONArray jArray; try{ jArray = new JSONArray(result); JSONObject json_data=null; int j=0; for(int i=0;i<jArray.length();i++){ Map<String,String> dataDb = new HashMap<String,String>(); json_data = jArray.getJSONObject(i); name=json_data.getString("name"); surname=json_data.getString("surname"); ++j; dataDb.put(POSITION, ""+j); dataDb.put(ONLINE_NAME, name); dataDb.put(ONLINE_SCORE, surname); listaDb.add(dataDb); } }catch(JSONException e1){ }catch (ParseException e1){ } return listaDb; }
Codice nella jsp:
$SQL ="SELECT name, surname FROM t_player"; $result = mysql_query($SQL); while ( $db_field = mysql_fetch_assoc($result) ) { $output[]=$db_field; } print(json_encode($output));
Post e inserimento dati:
public void insertPlayer(Player player){ InputStream is = null; try{ HttpClient httpclient = new DefaultHttpClient(); ArrayList<namevaluepair> nameValuePairs = new ArrayList<namevaluepair>(7); nameValuePairs.add(new BasicNameValuePair("name",player.getName())); nameValuePairs.add(new BasicNameValuePair("surname",player.getSurname())); HttpPost httppost = new HttpPost("http://wwwwww/insert.php"); //link httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); String responseBody =convertStreamToString(is); }catch(Exception e){ } }
Codice nella jsp:
$SQL = "insert into t_player ( name_player, surname_player) values ('".$_POST['name']."','".$_POST['surname']."')";