1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
|
import java.io.BufferedInputStream;
import java.io.IOException;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
/**
* Test de http client
*
@author phymbert
*
*/
public class TestHtmlClient
{
private static void processData(byte[]buffer,int i,int size,long total)
{
// Affiche le résultat dans la console
String data=new String(buffer,i,size);
System.out.println(data);
}
public static void main(String[]args){
// Le client HTTP
HttpClient client =new HttpClient();
// La méthode GET du protoccol HTTP
GetMethod method=new GetMethod("http://www.google.com");
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(1,false));
try{
// Execute la méthode HTTP
int statusCode=client.executeMethod(method);
// Vérifie le code de retour
if(statusCode!=HttpStatus.SC_OK){
return;
}
// Le buffer de lecture des données
BufferedInputStream br=null;
// 5 MO de buffer
byte[]buffer=new byte[(int)(5*Math.pow(2,20))];
// La taille total de la page
long size=0;
// La taille actuellement lue
int read=-1;
try{
//Ouvre le buffer de lecture
br=new BufferedInputStream(method.getResponseBodyAsStream());
// C'est partit on lit la page
while((read=br.read(buffer,0,buffer.length))>0){
// Traite les données
processData(buffer,0,read,size);
size+=read;
}
}catch(Exception e){
}finally{
if(br!=null)
try{
br.close();
}catch(Exception e){
}
}
}catch(HttpException e){
}catch(IOException e){
}finally{
// Release the connection.
method.releaseConnection();
}
}
/**
* Traite les données.
*
@param buffer Le buffer contenant les données
*
@param i L'index de départ des données à traiter
*
@param size La taille des données à traiter
*
@param total Le nombre de données total déjà traités
*/
private static void processData(byte[]buffer,int i,int size,long total)
{
// Affiche le résultat dans la console
String data=new String(buffer,i,size);
System.out.println(data);
}
} |
Partager