SlideShare une entreprise Scribd logo
Développer sur Android
Android Lab Test
www.AndroidLabTest.com
Facebook
Par Bruno Delb
www.youtube.com/androidlabtest
www.twitter.com/brunodelb | www.facebook.com/brunodelb | blog.brunodelb.com
www.facebook.com/Androidlabtest
Youtube
Siteofficiel
Leçon : Lecture HTTP
Lecture HTTP
• Dans cette leçon, vous allez apprendre à effectuer une
requête HTTP sur un serveur Web.
• Pour cela, vous allez utiliser le DefaultHttpClient,
HttpGet / HttpPost et un InputStream.
Lecture HTTP
• Pour effectuer une requête de type GET, utilisez la classe HttpGet :
HttpGet http = new HttpGet (new URI (url));
• Pour effectuer une requête de type POST, utilisez la classe HttpPost :
HttpPost http = new HttpPost (new URI (url));
• Pour ajouter un entête HTTP, utilisez la méthode addHeader() :
http.addHeader("pragma","no-cache");
Lecture HTTP
• Pour ajouter les données, utilisez un objet List <NameValuePair> pour les
stocker puis appelez la méthode setEntity :
http.setEntity(new UrlEncodedFormEntity (headers, HTTP.UTF_8));
• Pour exécuter la requête HTTP, utilisez la méthode execute() :
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(http);
• Pour lire les données retournées par le serveur, utilisez un InputStream :
InputStream inputStream = httpResponse.getEntity().getContent();
Lecture HTTP
• Pour lire le flux InputStream, utilisez un InputStreamReader :
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
• Lisez les données ligne par ligne grâce à un BufferedReader :
BufferedReader bufferedReader = new BufferedReader (inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("n");
}
Lecture HTTP
• Il faut ensuite fermer le InputStream :
inputStream.close();
• Le texte lu se trouve dans le StringBuilder :
String html = stringBuilder.toString();
Layout main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="URL" />
<EditText
android:id="@+id/et_url"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:text="http://www.google.com" />
Layout main.xml
<Button
android:id="@+id/btnDownload"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Download" />
<EditText
android:id="@+id/et_output"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10" />
</LinearLayout>
Fichier Main.java
public class Main extends Activity {
EditText et_output;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et_output = (EditText)findViewById (R.id.et_output);
Button btnDownload = (Button)findViewById (R.id.btnDownload);
btnDownload.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText et_url = (EditText)findViewById (R.id.et_url);
et_output.setText (getURL ("" + et_url.getText(), null));
}
});
}
Fichier Main.java
public String getURL (String url, List <NameValuePair> headers) {
try {
HttpGet httpGet = new HttpGet (new URI (url));
httpGet.addHeader("pragma","no-cache");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpGet);
InputStream inputStream = httpResponse.getEntity().getContent();
return inputStreamToString (inputStream);
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), 5000).show();
}
return "";
}
Fichier Main.java
public String inputStreamToString (InputStream inputStream) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader (inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
try {
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("n");
}
inputStream.close();
} catch (IOException e) {
}
return stringBuilder.toString();
}
}
Testez sur votre mobile
Network_Http
Retrouvez-moi sur ma chaîne AndroidLabTest …
Sur ma chaîne Youtube
https://www.youtube.com/user/mobiledevlabtest
Qui suis-je ?
Bruno Delb,
auteur du 1er livre francophone de développement d’application Java sur mobile (2002),
développeur d’applications mobiles & sociales,
parlez-moi de vos projets.
Et bien sûr sur mon site Web :
http://blog.brunodelb.com

Contenu connexe

PPTX
Ns python-flask
PDF
script site e-commerce -php
PPTX
URL-REWRITE HARIFI Madiha
PPS
Dansend de wereld rond
PPTX
Android Lab Test : Storage of data with SharedPreferences (english)
PPTX
Android Lab Test : Ecrire un texte sur le canevas (français)
PPTX
Android Lab Test : Reading the foot file list (english)
PDF
Loose Moissanite Gemstones for Jewelry
Ns python-flask
script site e-commerce -php
URL-REWRITE HARIFI Madiha
Dansend de wereld rond
Android Lab Test : Storage of data with SharedPreferences (english)
Android Lab Test : Ecrire un texte sur le canevas (français)
Android Lab Test : Reading the foot file list (english)
Loose Moissanite Gemstones for Jewelry

Similaire à Android Lab Test : La connectivité réseau avec HTTP (français) (12)

PDF
Tutorial android
PDF
Le Guide de Développement pour Android
PDF
Chapitre 2 elements graphiques android
PDF
Les vues (views) sous android
PDF
Tutorial android
PDF
Tutorial android - créer des apps
PPT
Upload - Download
PPT
Upload - Download
PDF
Chapitre 3 activites et intents
DOCX
Chap android
PDF
Développer une application android en 2015
DOCX
Activity
Tutorial android
Le Guide de Développement pour Android
Chapitre 2 elements graphiques android
Les vues (views) sous android
Tutorial android
Tutorial android - créer des apps
Upload - Download
Upload - Download
Chapitre 3 activites et intents
Chap android
Développer une application android en 2015
Activity
Publicité

Plus de Bruno Delb (20)

PPTX
Introduction to Swift (tutorial)
PPTX
Android Lab Test : Using the sensor gyroscope (english)
PPTX
Android Lab Test : Using the network with HTTP (english)
PPTX
Android Lab Test : Managing sounds with SoundPool (english)
PPTX
Android Lab Test : Using the text-to-speech (english)
PPTX
Android Lab Test : Creating a menu dynamically (english)
PPTX
Android Lab Test : Creating a dialog Yes/No (english)
PPTX
Android Lab Test : The styles of views (english)
PPTX
Android Lab Test : Creating a menu context (english)
PPTX
Android Lab Test : Using the camera preview (english)
PPTX
Android Lab Test : The views, the Gallery (english)
PPTX
Android Lab Test : Using the WIFI (english)
PPTX
Android Lab Test : Managing the telephone calls (english)
PPTX
Android Lab Test : Reading the SMS-inbox (english)
PPTX
Android Lab Test : Installation of application in Java (english)
PPTX
Android Lab Test : Le capteur gyroscope (français)
PPTX
Android Lab Test : Les threads (français)
PPTX
Android Lab Test : L'installation d'une application en Java (français)
PPTX
Android Lab Test : Le stockage avec SharedPreferences (français)
PPTX
Android Lab Test : La reconnaissance vocale (français)
Introduction to Swift (tutorial)
Android Lab Test : Using the sensor gyroscope (english)
Android Lab Test : Using the network with HTTP (english)
Android Lab Test : Managing sounds with SoundPool (english)
Android Lab Test : Using the text-to-speech (english)
Android Lab Test : Creating a menu dynamically (english)
Android Lab Test : Creating a dialog Yes/No (english)
Android Lab Test : The styles of views (english)
Android Lab Test : Creating a menu context (english)
Android Lab Test : Using the camera preview (english)
Android Lab Test : The views, the Gallery (english)
Android Lab Test : Using the WIFI (english)
Android Lab Test : Managing the telephone calls (english)
Android Lab Test : Reading the SMS-inbox (english)
Android Lab Test : Installation of application in Java (english)
Android Lab Test : Le capteur gyroscope (français)
Android Lab Test : Les threads (français)
Android Lab Test : L'installation d'une application en Java (français)
Android Lab Test : Le stockage avec SharedPreferences (français)
Android Lab Test : La reconnaissance vocale (français)
Publicité

Dernier (20)

PPTX
SESSION2-SUPPORT-DE-COURS-FLEC-(Future leader en énergie au Cameroun)-CECOSDA...
PPTX
Marketing de l'Artisanat et la technique
PDF
585-developpement-d-une-application-avec-python-fr-en-business.pdf
PPTX
Présentation Personal Branding J2025.pptx_20250218_132749_0000.pptx_20250610_...
PPTX
Formation Equipement de protection .pptx
PPT
مبادئ و هدف الحركة الكشفية عرض تقديمي.ppt
PPTX
Fondamentaux du LMD.pptx pour les etudiants
PPTX
Conception de documents et d'interfaces numériques.pptx
PPT
Les moyens de transport-2023.ppt french language teaching ppt
PDF
_LEAN_MANAGEMENT_Am_lioration_continue_�_1724845102.pdf
PPTX
SESSION5-SUPPORT-DE-COURS-FLEC-(Future leader en énergie au Cameroun)-CECOSDA...
PDF
Referentiel des metiers cadres dans la banque
PPTX
Hopital bonne sante.pptxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
PPTX
le-present-de-lindicatif-ou-le-subjonctif-present-exercice-grammatical-feuill...
PPTX
Informatique pour débutants niveau 1.pptx
PPTX
le subjonctif présent, Conjugaison français
PDF
🎓 Le Secret des Profs Captivants - 💡 Pourquoi l’oral est stratégique en class...
PPTX
Copie de Présentation Personal Branding J2025.pptx_20250610_120558_0000.pptx
PPTX
Le rendez-vous de l'été.pptx Film français
PPTX
risque environnema et mesure protect.pptx
SESSION2-SUPPORT-DE-COURS-FLEC-(Future leader en énergie au Cameroun)-CECOSDA...
Marketing de l'Artisanat et la technique
585-developpement-d-une-application-avec-python-fr-en-business.pdf
Présentation Personal Branding J2025.pptx_20250218_132749_0000.pptx_20250610_...
Formation Equipement de protection .pptx
مبادئ و هدف الحركة الكشفية عرض تقديمي.ppt
Fondamentaux du LMD.pptx pour les etudiants
Conception de documents et d'interfaces numériques.pptx
Les moyens de transport-2023.ppt french language teaching ppt
_LEAN_MANAGEMENT_Am_lioration_continue_�_1724845102.pdf
SESSION5-SUPPORT-DE-COURS-FLEC-(Future leader en énergie au Cameroun)-CECOSDA...
Referentiel des metiers cadres dans la banque
Hopital bonne sante.pptxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
le-present-de-lindicatif-ou-le-subjonctif-present-exercice-grammatical-feuill...
Informatique pour débutants niveau 1.pptx
le subjonctif présent, Conjugaison français
🎓 Le Secret des Profs Captivants - 💡 Pourquoi l’oral est stratégique en class...
Copie de Présentation Personal Branding J2025.pptx_20250610_120558_0000.pptx
Le rendez-vous de l'été.pptx Film français
risque environnema et mesure protect.pptx

Android Lab Test : La connectivité réseau avec HTTP (français)

  • 1. Développer sur Android Android Lab Test www.AndroidLabTest.com Facebook Par Bruno Delb www.youtube.com/androidlabtest www.twitter.com/brunodelb | www.facebook.com/brunodelb | blog.brunodelb.com www.facebook.com/Androidlabtest Youtube Siteofficiel Leçon : Lecture HTTP
  • 2. Lecture HTTP • Dans cette leçon, vous allez apprendre à effectuer une requête HTTP sur un serveur Web. • Pour cela, vous allez utiliser le DefaultHttpClient, HttpGet / HttpPost et un InputStream.
  • 3. Lecture HTTP • Pour effectuer une requête de type GET, utilisez la classe HttpGet : HttpGet http = new HttpGet (new URI (url)); • Pour effectuer une requête de type POST, utilisez la classe HttpPost : HttpPost http = new HttpPost (new URI (url)); • Pour ajouter un entête HTTP, utilisez la méthode addHeader() : http.addHeader("pragma","no-cache");
  • 4. Lecture HTTP • Pour ajouter les données, utilisez un objet List <NameValuePair> pour les stocker puis appelez la méthode setEntity : http.setEntity(new UrlEncodedFormEntity (headers, HTTP.UTF_8)); • Pour exécuter la requête HTTP, utilisez la méthode execute() : DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse = httpClient.execute(http); • Pour lire les données retournées par le serveur, utilisez un InputStream : InputStream inputStream = httpResponse.getEntity().getContent();
  • 5. Lecture HTTP • Pour lire le flux InputStream, utilisez un InputStreamReader : InputStreamReader inputStreamReader = new InputStreamReader(inputStream); • Lisez les données ligne par ligne grâce à un BufferedReader : BufferedReader bufferedReader = new BufferedReader (inputStreamReader); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line).append("n"); }
  • 6. Lecture HTTP • Il faut ensuite fermer le InputStream : inputStream.close(); • Le texte lu se trouve dans le StringBuilder : String html = stringBuilder.toString();
  • 7. Layout main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="URL" /> <EditText android:id="@+id/et_url" android:layout_width="fill_parent" android:layout_height="wrap_content" android:ems="10" android:text="http://www.google.com" />
  • 9. Fichier Main.java public class Main extends Activity { EditText et_output; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); et_output = (EditText)findViewById (R.id.et_output); Button btnDownload = (Button)findViewById (R.id.btnDownload); btnDownload.setOnClickListener(new OnClickListener() { public void onClick(View v) { EditText et_url = (EditText)findViewById (R.id.et_url); et_output.setText (getURL ("" + et_url.getText(), null)); } }); }
  • 10. Fichier Main.java public String getURL (String url, List <NameValuePair> headers) { try { HttpGet httpGet = new HttpGet (new URI (url)); httpGet.addHeader("pragma","no-cache"); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse = httpClient.execute(httpGet); InputStream inputStream = httpResponse.getEntity().getContent(); return inputStreamToString (inputStream); } catch (Exception e) { Toast.makeText(this, e.getMessage(), 5000).show(); } return ""; }
  • 11. Fichier Main.java public String inputStreamToString (InputStream inputStream) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader (inputStreamReader); StringBuilder stringBuilder = new StringBuilder(); try { String line; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line).append("n"); } inputStream.close(); } catch (IOException e) { } return stringBuilder.toString(); } }
  • 12. Testez sur votre mobile Network_Http
  • 13. Retrouvez-moi sur ma chaîne AndroidLabTest … Sur ma chaîne Youtube https://www.youtube.com/user/mobiledevlabtest Qui suis-je ? Bruno Delb, auteur du 1er livre francophone de développement d’application Java sur mobile (2002), développeur d’applications mobiles & sociales, parlez-moi de vos projets. Et bien sûr sur mon site Web : http://blog.brunodelb.com