Partage
  • Partager sur Facebook
  • Partager sur Twitter

Envoi de fichiers par HTTP POST

    18 février 2009 à 14:22:47

    Bonjour,

    Dans mon applet j'ai une méthode chargée d'envoyer par HTTPS POST 2 fichiers ; voici la classe que j'ai créée pour construire ma requête HTTPS :

    import java.net.URLConnection;
    import java.net.URL;
    import java.io.File;
    import java.io.InputStream;
    import java.util.Random;
    import java.io.OutputStream;
    import java.io.FileInputStream;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    
    public class FileHttpPost
    {
        private URLConnection connexion;
        private String boundary;
        private String encapsulationBoundary;
        private OutputStream outputStream;
    
        public FileHttpPost(String adresse, long contentLength) throws Exception
        {
            URL url = new URL(adresse);
            this.connexion = url.openConnection();
            this.connexion.setDoOutput(true);
            this.buildBoundary();
            this.connexion.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + this.boundary);
            this.connexion.setRequestProperty("Content-Length", Long.toHexString(contentLength));
    
            this.outputStream = this.connexion.getOutputStream();
        }
    
        protected boolean post()
        {
            InputStream inputStream=null;
    
            try
            {
                String lastBoundary = this.encapsulationBoundary + "--";
                this.writeData(lastBoundary);
                this.outputStream.close();
                inputStream = this.connexion.getInputStream();
    
                // Get the response
                BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                while ((line = rd.readLine()) != null)
                {
                    if(line.compareTo("ERREUR PAS DE FICHIER ENVOYE")==0)
                        return false;
                }
    
            }
            catch(Exception e) { e.printStackTrace(); }
    
            return true;
        }
    
        protected boolean addFile(String fieldName, String filePath, int zoneId, long fileLength) throws Exception
        {
            File fileToPost = new File(filePath);
            InputStream inputStream = new FileInputStream(fileToPost);
    
            this.writeData(this.encapsulationBoundary);
            this.writeData(this.getFileHeader(fieldName, filePath));
    
            byte[] buf = new byte[1024];
            int nread, total=0;
            synchronized (inputStream)
            {
              while((nread = inputStream.read(buf, 0, buf.length)) >= 0)
              {
                total += nread;
                this.outputStream.write(buf, 0, nread);
                switch(zoneId)
                {
                    case 1:
                        interscanJava.apercu.setTransfert1(DocumentReader.convertOctet(total) + "/" + DocumentReader.convertOctet(fileLength) + " envoyés");
                        break;
                    case 2:
                        interscanJava.apercu.setTransfert2(DocumentReader.convertOctet(total) +"/" + DocumentReader.convertOctet(fileLength) + " envoyés");
                        break;
                    default:
                        break;
                }
              }
            }
            this.outputStream.flush();
            buf = null;
    
            this.writeData("");
    
            return true;
        }
    
        protected String getFileHeader(String fieldName, String filePath) throws Exception
        {
            String contentDisposition = "Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + filePath + "\"";
            String contentType = "Content-Type:" + this.connexion.guessContentTypeFromName(filePath);
            String fileData = contentDisposition + "\r\n" + contentType + "\r\n";
    
            return fileData;
        }
    
        protected boolean writeData(String data) throws Exception
        {
            String toWrite = data + "\r\n";
            this.outputStream.write(toWrite.getBytes());
    
            return true;
        }
    
        private boolean buildBoundary()
        {
            String boundaryId = "";
    
            for(int i=0 ; i<3 ; i++)
                boundaryId = boundaryId + this.buildBoundaryPart();
    
            this.boundary = "---------------------------" + boundaryId;
            this.encapsulationBoundary = "--" + this.boundary;
    
            return true;
        }
    
        private String buildBoundaryPart()
        {
            Random random = new Random();
    
            return Long.toString(random.nextLong(), 36);
        }
    
    }
    


    Le transfert se fait bien mais j'aimerais pouvoir afficher dans mon interface l'état du transfert de chacun des 2 fichiers. Je croyait le faire dans ma méthode addFile() avec setTransfert1 qui met à jour l'affichage concernant le fichier 1 et setTransfert2 pour le fichier 2, mais en fait il semble que ce que j'affiche correspond à l'écriture de mon OutputStream, non au transfert à l'URL donnée.

    Il aurait fallu que j'ai le suivi de ce qui se passe dans this.connexion.getInputStream(); car apparament c'est là que les fichiers partent vraiment. D'ailleurs je ne comprends pas pourquoi je dois utiliser getInputStream() pour que les fichiers partent (si je mets en commentaire le getInputStream() les fichiers ne sont pas envoyés) ; une explication?

    Merci d'avance pour votre aide.

    PS: je me suis aidé de cette page : http://www.devx.com/Java/Article/17679/1763/page/2, le formulaire à qui j'envoie les fichiers est presque pareil que celui de l'exemple 3.
    • Partager sur Facebook
    • Partager sur Twitter

    Envoi de fichiers par HTTP POST

    × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
    × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
    • Editeur
    • Markdown