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
| /*
* UrlUtils.java
*
* Created on 7 mai 2007, 22:52
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package javaapplication3;
import java.net.*;
import java.io.*;
/**
*
* @author Jordan
*/
public class UrlUtils {
public UrlUtils(String HOST) {
try {
URL racine = new URL(HOST);
getFile(racine);
} catch (MalformedURLException e){
System.err.println(HOST + " : URL non comprise.");
} catch (IOException e) {
System.err.println(e);
}
}
public void getFile(URL u) throws IOException {
URLConnection conn = u.openConnection();
String FileType = conn.getContentType();
int FileLenght = conn.getContentLength();
if (FileLenght == -1) {
throw new IOException("Fichier non valide.");
}
InputStream in = conn.getInputStream();
String FileName = u.getFile();
FileName = FileName.substring(FileName.lastIndexOf('/') + 1);
FileOutputStream WritenFile = new FileOutputStream(FileName);
byte[]buff = new byte[1024];
int l = in.read(buff);
while(l>0)
{
WritenFile.write(buff, 0, l);
l = in.read(buff);
}
WritenFile.flush();
WritenFile.close();
}
public void doPost(String adresse){
OutputStreamWriter writer = null;
BufferedReader reader = null;
try {
//encodage des paramètres de la requête
String donnees = URLEncoder.encode("clef", "UTF-8")+
"="+URLEncoder.encode("valeur", "UTF-8");
donnees += "&"+URLEncoder.encode("autreClef", "UTF-8")+
"=" + URLEncoder.encode("autreValeur", "UTF-8");
//création de la connection
URL url = new URL(adresse);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
//envoi de la requête
writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(donnees);
writer.flush();
//lecture de la réponse
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String ligne;
while ((ligne = reader.readLine()) != null) {
System.out.println(ligne);
}
}catch (Exception e) {
e.printStackTrace();
}finally{
try{writer.close();}catch(Exception e){}
try{reader.close();}catch(Exception e){}
}
}
} |
Partager