class HttpTask extends AsyncTask<String, Void, HttpResponse> { private Exception httpException = null; protected HttpResponse doInBackground(String... urls) { try { HttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost(urls[0]); // ... code return httpClient.execute(post); } catch (Exception e) { httpException = e; return null; } } protected void onPostExecute(final HttpResponse response) { /* ici tu peux tester l'exception ainsi que la réponse */ } }
new HttpTask().execute("http://10.188.171.170/gsc/reception.php");
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import android.app.Activity; import android.os.AsyncTask; @SuppressWarnings("deprecation") public class HttpGetTask<T extends Activity & HttpGetTaskListener> extends AsyncTask<String, Void, JSONArray> { private final T t; public HttpGetTask(final T t) { this.t = t; } @Override protected JSONArray doInBackground(final String... uril) { JSONArray result = null; BufferedReader reader = null; final HttpClient client = new DefaultHttpClient(); final HttpGet get = new HttpGet(); try { final URI uri = new URI(uril[0]); get.setURI(uri); final HttpResponse response = client.execute(get); final StatusLine statusLine = response.getStatusLine(); final int code = statusLine.getStatusCode(); if (code == 200) { final StringBuilder sb = new StringBuilder(); final HttpEntity entity = response.getEntity(); final InputStream content = entity.getContent(); reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) sb.append(line); result = new JSONArray(sb.toString()); } else { throw new IOException("The server has responded an error " + code); } } catch (final Exception e) { t.runOnUiThread(new Runnable() { @Override public void run() { t.onTaskError(e); } }); } finally { if (reader != null) { try { reader.close(); } catch (final IOException e) { } } } return result; } @Override protected void onPostExecute(final JSONArray response) { try { for (int i = 0; i < response.length(); i++) t.onTaskResponse(response.getJSONObject(i).getString("message")); t.onTaskFinished(); } catch (final Exception e) { t.onTaskError(e); } } }
<?php $output = array(); for($i = 0; $i < 10; $i++) { $row["message"] = "test_$i"; $output[] = $row; } header('Content-type: application/json'); exit(json_encode($output)); ?>
<uses-permission android:name="android.permission.INTERNET"/>dans le manifest. Voici mon code
package com.example.gsctutandro; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { EditText edtMsg; Button btnEnvoyer; String resultat = null; InputStream is = null; StringBuilder sb = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edtMsg = (EditText)findViewById(R.id.edtMsg); btnEnvoyer = (Button)findViewById(R.id.btnEnvoyer); } public void envoyerMessage(View v){ HttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost("http://10.188.171.170/gsc/reception.php"); String msg = edtMsg.getText().toString(); if(msg.length() > 0){ try{ List<NameValuePair> donnees = new ArrayList<NameValuePair>(1); donnees.add(new BasicNameValuePair("message", msg)); post.setEntity(new UrlEncodedFormEntity(donnees)); httpClient.execute(post); edtMsg.setText(""); Toast.makeText(this, "Message envoyé", Toast.LENGTH_SHORT).show(); } catch(ClientProtocolException e){ e.printStackTrace(); } catch(IOException e){ e.printStackTrace(); } } else Toast.makeText(this, "Ce champ ne peut être vide", Toast.LENGTH_SHORT).show(); } }
Vous n’avez pas trouvé la réponse que vous recherchez ?
Posez votre questionimport java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.os.AsyncTask; import android.widget.Toast; public class HttpGetTask extends AsyncTask<String, Void, HttpResponse>{ @Override protected HttpResponse doInBackground(String... uril) { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(); try{ URI uri = new URI(uril[0]); get.setURI(uri); return client.execute(get); } catch(Exception e){ e.printStackTrace(); return null; } } protected void onGetExecute(final HttpResponse response) { }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { Button btnRecuperer; TextView txtMessage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnRecuperer = (Button)findViewById(R.id.lblRecuperer); txtMessage = (TextView)findViewById(R.id.txtMessage); } public void recupererMessage(View v){ HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(); StringBuilder sb = new StringBuilder(""); BufferedReader br = null; try{ HttpResponse reponse = new HttpGetTask().execute("http://10.188.171.170/gsc/envoi.php").get(); InputStream is = reponse.getEntity().getContent(); br = new BufferedReader(new InputStreamReader(is)); String ligneLue = br.readLine(); while(ligneLue != null){ sb.append(ligneLue); sb.append("\n"); ligneLue = br.readLine(); } } catch(Exception e){ e.printStackTrace(); } finally{ if(br != null){ try{ br.close(); } catch(IOException e){ e.printStackTrace(); } } } try{ JSONArray jArray = new JSONArray(sb.toString()); for(int i = 0; i < jArray.length(); i++){ txtMessage.append(jArray.getJSONObject(i).getString("message")); txtMessage.append("\n"); } }catch(JSONException je){ je.printStackTrace(); } } }
public interface HttpGetTaskListener { public void onTaskResponse(final String text); public void onTaskError(final Throwable t); public void onTaskFinished(); }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import android.app.Activity; import android.os.AsyncTask; @SuppressWarnings("deprecation") public class HttpGetTask<T extends Activity & HttpGetTaskListener> extends AsyncTask<String, Void, HttpResponse> { private final T t; public HttpGetTask(final T t) { this.t = t; } @Override protected HttpResponse doInBackground(final String... uril) { final HttpClient client = new DefaultHttpClient(); final HttpGet get = new HttpGet(); try { final URI uri = new URI(uril[0]); get.setURI(uri); return client.execute(get); } catch (final Exception e) { e.printStackTrace(); return null; } } @Override protected void onPostExecute(final HttpResponse response) { BufferedReader reader = null; try { final StatusLine statusLine = response.getStatusLine(); final int code = statusLine.getStatusCode(); if (code == 200) { final StringBuilder sb = new StringBuilder(); final HttpEntity entity = response.getEntity(); final InputStream content = entity.getContent(); reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) sb.append(line); final JSONArray jArray = new JSONArray(sb.toString()); t.runOnUiThread(new Runnable() { @Override public void run() { for (int i = 0; i < jArray.length(); i++) { try { t.onTaskResponse(jArray.getJSONObject(i).getString("message")); } catch (final JSONException e) { t.onTaskError(e); return; } } t.onTaskFinished(); } }); } else { throw new IOException("The server has responded an error " + code); } } catch (final Exception e) { t.runOnUiThread(new Runnable() { @Override public void run() { t.onTaskError(e); } }); } finally { if (reader != null) { try { reader.close(); } catch (final IOException e) { } } } } }
import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity implements HttpGetTaskListener { Button btnRecuperer; TextView txtMessage; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnRecuperer = (Button)findViewById(R.id.lblRecuperer); txtMessage = (TextView)findViewById(R.id.txtMessage); } public void recupererMessage(final View v) { /* veroullage du bouton pour eviter les task multiples */ btnRecuperer.setEnabled(false); /* déclenchement de la requête */ new HttpGetTask<MainActivity>(this) .execute("http://10.188.171.170/gsc/envoi.php"); } @Override public void onTaskResponse(final String text) { txtMessage.append(text); txtMessage.append("\n"); } @Override public void onTaskError(final Throwable t) { Log.e(getClass().getSimpleName(), "Exception: " + t.getMessage(), t); /* Restauration du bouton */ btnRecuperer.setEnabled(true); } @Override public void onTaskFinished() { /* Restauration du bouton */ btnRecuperer.setEnabled(true); } }
sb.toString()il était vide
$db = mysqli_connect('localhost', 'root', ''); mysqli_select_db($db,'gsctuto'); // Cette ligne permet d'effectuer notre requete $sql = mysqli_query($db,"SELECT message FROM information"); // Recupérer les données dans un tableau while($resultat = mysqli_fetch_assoc($sql)) $sortie[] = $resultat; // Encoder les données sous format JSON $jsob = json_encode($sortie); print($jsob);