Télécharger des fichiers du client Java vers un serveur HTTP


Je voudrais télécharger quelques fichiers sur un serveur HTTP. Fondamentalement, ce dont j'ai besoin, c'est d'une sorte de demande POST au serveur avec quelques paramètres et les fichiers. J'ai vu des exemples de téléchargement de fichiers, mais je n'ai pas trouvé comment passer des paramètres supplémentaires.

Quelle est la solution la plus simple et la plus libre de le faire? Quelqu'un a-t-il des exemples de téléchargement de fichiers que je pourrais étudier? J'ai cherché sur Google pendant quelques heures, mais (peut-être que c'est juste un de ces jours) je n'ai pas trouvé exactement ce que je nécessaire. La meilleure solution serait quelque chose qui n'implique aucune classe ou bibliothèque tierce.

Author: BalusC, 2010-03-18

6 answers

Vous utiliseriez normalementjava.net.URLConnection pour lancer des requêtes HTTP. Vous utiliseriez également normalement multipart/form-data encodage pour le contenu de poste mixte (données binaires et de caractères). Cliquez sur le lien, il contient des informations et un exemple comment composer un corps de requête multipart/form-data. La spécification est décrite plus en détail dans RFC2388.

Voici un exemple de coup d'envoi:

String url = "http://example.com/upload";
String charset = "UTF-8";
String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.

URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

try (
    OutputStream output = connection.getOutputStream();
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) {
    // Send normal param.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
    writer.append(CRLF).append(param).append(CRLF).flush();

    // Send text file.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF);
    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
    writer.append(CRLF).flush();
    Files.copy(textFile.toPath(), output);
    output.flush(); // Important before continuing with writer!
    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

    // Send binary file.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
    writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
    writer.append("Content-Transfer-Encoding: binary").append(CRLF);
    writer.append(CRLF).flush();
    Files.copy(binaryFile.toPath(), output);
    output.flush(); // Important before continuing with writer!
    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

    // End of multipart/form-data.
    writer.append("--" + boundary + "--").append(CRLF).flush();
}

// Request is lazily fired whenever you need to obtain information about response.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode); // Should be 200

Ce code est moins verbeux lorsque vous utilisez une bibliothèque tierce comme Apache Commons HttpComponents Client .

L'Apache CommonsFileUpload comme certains le suggèrent à tort ici n'est d'intérêt que pour lecôté serveur . Vous ne pouvez pas l'utiliser et n'en avez pas besoin côté client.

Voir aussi

 79
Author: BalusC, 2017-05-23 11:54:44

Voici comment vous le feriez avec Apache HttpClient (cette solution est pour ceux qui ne craignent pas d'utiliser une bibliothèque tierce):

    MultipartEntity entity = new MultipartEntity();
    entity.addPart("file", new FileBody(file));

    HttpPost request = new HttpPost(url);
    request.setEntity(entity);

    HttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(request);
 22
Author: Emmanuel Bourg, 2013-09-06 09:59:38

Cliquez sur le lien pour obtenir un exemple de téléchargement de fichier clint java avec apache HttpComponents

Http://hc.apache.org/httpcomponents-client-ga/httpmime/examples/org/apache/http/examples/entity/mime/ClientMultipartFormPost.java

Et le lien downalod de la bibliothèque

Https://hc.apache.org/downloads.cgi

Utiliser 4.5.3.zip ça fonctionne bien dans mon code

Et mon code de travail..

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class ClientMultipartFormPost {

     public static void main(String[] args) throws Exception {

          CloseableHttpClient httpclient = HttpClients.createDefault();
          try {
             HttpPost httppost = new HttpPost("http://localhost:8080/MyWebSite1/UploadDownloadFileServlet");

             FileBody bin = new FileBody(new File("E:\\meter.jpg"));
             StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

             HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("bin", bin)
                .addPart("comment", comment)
                .build();


             httppost.setEntity(reqEntity);

             System.out.println("executing request " + httppost.getRequestLine());
             CloseableHttpResponse response = httpclient.execute(httppost);
           try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                     System.out.println("Response content length: " +    resEntity.getContentLength());
                }
              EntityUtils.consume(resEntity);
             } finally {
                 response.close();
            }
       } finally {
          httpclient.close();
      }
   }

}
 3
Author: Prashant, 2017-03-02 13:18:23
public static String simSearchByImgURL(int  catid ,String imgurl) throws IOException{
    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    String result =null;
    try {
        HttpPost httppost = new HttpPost("http://api0.visualsearchapi.com:8084/vsearchtech/api/v1.0/apisim_search");
        StringBody catidBody = new StringBody(catid+"" , ContentType.TEXT_PLAIN);
        StringBody keyBody = new StringBody(APPKEY , ContentType.TEXT_PLAIN);
        StringBody langBody = new StringBody(LANG , ContentType.TEXT_PLAIN);
        StringBody fmtBody = new StringBody(FMT , ContentType.TEXT_PLAIN);
        StringBody imgurlBody = new StringBody(imgurl , ContentType.TEXT_PLAIN);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addPart("apikey", keyBody).addPart("catid", catidBody)
        .addPart("lang", langBody)
        .addPart("fmt", fmtBody)
        .addPart("imgurl", imgurlBody);
        HttpEntity reqEntity =  builder.build();
        httppost.setEntity(reqEntity);
        response = httpClient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
           // result = ConvertStreamToString(resEntity.getContent(), "UTF-8");
            String charset = "UTF-8";   
          String content=EntityUtils.toString(response.getEntity(), charset);   
            System.out.println(content);
        }
        EntityUtils.consume(resEntity);
    }catch(Exception e){
        e.printStackTrace();
    }finally {
        response.close();
        httpClient.close();
    }
    return result;
}
 0
Author: deeplinks, 2016-09-04 11:19:29
protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();

    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    String uploadFolder = getServletContext().getRealPath("")
            + File.separator + DATA_DIRECTORY;//DATA_DIRECTORY is directory where you upload this file on the server

    ServletFileUpload upload = new ServletFileUpload(factory);

    upload.setSizeMax(MAX_REQUEST_SIZE);//MAX_REQUEST_SIZE is the size which size you prefer

Et utilisez <form enctype="multipart/form-data"> et utilisez <input type="file"> dans le html

 -3
Author: user1693371, 2014-06-05 04:34:09

Cela pourrait dépendre de votre framework. (pour chacun d'eux pourrait exister une solution plus facile).

, Mais pour répondre à votre question: il y a beaucoup de bibliothèques externes pour cette fonctionnalité. Regardez ici comment utiliser apache commons fileupload.

 -6
Author: Karussell, 2010-03-18 11:52:34