[Java] Récupération de page web

[Java] Récupération de page web.
1/ Création du répertoire de travail :

➜  ~ mkdir -p JAVA
➜  ~ cd JAVA
➜  JAVA

2/ Création du répertoire de l’application :

➜  JAVA mkdir -p net/gandi

3/ Exemple de récupération de page :
Ouvrir :

net/gandi/HttpURLConnectionExample.java

Ajouter :

package net.gandi;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
// http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/
public class HttpURLConnectionExample {
    private final String USER_AGENT = "Mozilla/5.0";
    public static void main(String[] args) throws Exception {
        HttpURLConnectionExample http = new HttpURLConnectionExample();
        System.out.println("Testing 1 - Send Http GET request");
        http.sendGet();
    }
    // HTTP GET request
    private void sendGet() throws Exception {
        String url = "http://www.gandi.net";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // optional default is GET
        con.setRequestMethod("GET");
        //add request header
        con.setRequestProperty("User-Agent", USER_AGENT);
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);
        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        //print result
        System.out.println(response.toString());
    }
}

4/ Compilation :

➜  JAVA javac net/gandi/HttpURLConnectionExample.java

5/ Exécution :

➜  JAVA java net.gandi.HttpURLConnectionExample

6/ Lien :
http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/

Comments are closed, but trackbacks and pingbacks are open.