Envoi de fichiers à l’aide de POST avec HttpURLConnection

Comme les développeurs Android recommandent d’utiliser la classe HttpURLConnection , je me demandais si quelqu’un pouvait me donner un bon exemple sur la façon d’envoyer un “fichier” bitmap (en fait un stream en mémoire) via POST vers un serveur Apache HTTP. Je ne suis pas intéressé par les cookies ou l’authentification ou quelque chose de compliqué, mais je veux juste avoir une implémentation fiable et logique. Tous les exemples que j’ai vus ici ressemblent plus à “Essayons ceci et peut-être que ça marche”.

En ce moment, j’ai ce code:

 URL url; HttpURLConnection urlConnection = null; try { url = new URL("http://example.com/server.cgi"); urlConnection = (HttpURLConnection) url.openConnection(); } catch (Exception e) { this.showDialog(getApplicationContext(), e.getMessage()); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } 

où showDialog doit simplement afficher un AlertDialog (en cas d’adresse URL invalide?).

Maintenant, supposons que je génère un bitmap comme ceci: Bitmap image = this.getBitmap() dans un contrôle dérivé de View et que je souhaite envoyer via POST. Quelle serait la procédure appropriée pour réaliser une telle chose? Quelles classes dois-je utiliser? Puis-je utiliser HttpPost comme dans cet exemple ? Si oui, comment pourrais-je construire InputStreamEntity pour mon bitmap? Je trouverais révoltant d’être obligé de stocker d’abord le bitmap dans un fichier sur le périphérique.


Je devrais également mentionner que je dois vraiment envoyer chaque pixel non modifié du bitmap original au serveur, donc je ne peux pas le convertir en JPEG.

Je ne sais pas pourquoi la classe HttpURLConnection ne fournit aucun moyen d’envoyer des fichiers sans avoir à composer manuellement le wrapper de fichier. Voici ce que j’ai fini par faire, mais si quelqu’un connaît une meilleure solution, faites-le moi savoir.

Des données d’entrée:

 Bitmap bitmap = myView.getBitmap(); 

Choses statiques:

 Ssortingng attachmentName = "bitmap"; Ssortingng attachmentFileName = "bitmap.bmp"; Ssortingng crlf = "\r\n"; Ssortingng twoHyphens = "--"; Ssortingng boundary = "*****"; 

Configurer la demande:

 HttpURLConnection httpUrlConnection = null; URL url = new URL("http://example.com/server.cgi"); httpUrlConnection = (HttpURLConnection) url.openConnection(); httpUrlConnection.setUseCaches(false); httpUrlConnection.setDoOutput(true); httpUrlConnection.setRequestMethod("POST"); httpUrlConnection.setRequestProperty("Connection", "Keep-Alive"); httpUrlConnection.setRequestProperty("Cache-Control", "no-cache"); httpUrlConnection.setRequestProperty( "Content-Type", "multipart/form-data;boundary=" + this.boundary); 

Démarrer le wrapper de contenu:

 DataOutputStream request = new DataOutputStream( httpUrlConnection.getOutputStream()); request.writeBytes(this.twoHyphens + this.boundary + this.crlf); request.writeBytes("Content-Disposition: form-data; name=\"" + this.attachmentName + "\";filename=\"" + this.attachmentFileName + "\"" + this.crlf); request.writeBytes(this.crlf); 

Convertir Bitmap en ByteBuffer :

 //I want to send only 8 bit black & white bitmaps byte[] pixels = new byte[bitmap.getWidth() * bitmap.getHeight()]; for (int i = 0; i < bitmap.getWidth(); ++i) { for (int j = 0; j < bitmap.getHeight(); ++j) { //we're interested only in the MSB of the first byte, //since the other 3 bytes are identical for B&W images pixels[i + j] = (byte) ((bitmap.getPixel(i, j) & 0x80) >> 7); } } request.write(pixels); 

Fin du wrapper de contenu:

 request.writeBytes(this.crlf); request.writeBytes(this.twoHyphens + this.boundary + this.twoHyphens + this.crlf); 

Flush buffer de sortie:

 request.flush(); request.close(); 

Avoir une réponse:

 InputStream responseStream = new BufferedInputStream(httpUrlConnection.getInputStream()); BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream)); Ssortingng line = ""; SsortingngBuilder ssortingngBuilder = new SsortingngBuilder(); while ((line = responseStreamReader.readLine()) != null) { ssortingngBuilder.append(line).append("\n"); } responseStreamReader.close(); Ssortingng response = ssortingngBuilder.toSsortingng(); 

Fermer le stream de réponse:

 responseStream.close(); 

Ferme la connexion:

 httpUrlConnection.disconnect(); 

PS: Bien sûr, j’ai dû envelopper la requête en private class AsyncUploadBitmaps extends AsyncTask afin de rendre la plateforme Android heureuse, car elle n’aime pas avoir de requêtes réseau sur le thread principal.

J’ai trouvé une meilleure façon d’envoyer des fichiers en utilisant HttpURLConnection en utilisant MultipartEntity

 private static Ssortingng multipost(Ssortingng urlSsortingng, MultipartEntity reqEntity) { try { URL url = new URL(urlSsortingng); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.addRequestProperty("Content-length", reqEntity.getContentLength()+""); conn.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue()); OutputStream os = conn.getOutputStream(); reqEntity.writeTo(conn.getOutputStream()); os.close(); conn.connect(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { return readStream(conn.getInputStream()); } } catch (Exception e) { Log.e(TAG, "multipart post error " + e + "(" + urlSsortingng + ")"); } return null; } private static Ssortingng readStream(InputStream in) { BufferedReader reader = null; SsortingngBuilder builder = new SsortingngBuilder(); try { reader = new BufferedReader(new InputStreamReader(in)); Ssortingng line = ""; while ((line = reader.readLine()) != null) { builder.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return builder.toSsortingng(); } 

En supposant que vous téléchargez une image avec des données bitmap:

  Bitmap bitmap = ...; Ssortingng filename = "filename.png"; ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos); ContentBody contentPart = new ByteArrayBody(bos.toByteArray(), filename); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntity.addPart("picture", contentPart); Ssortingng response = multipost("http://server.com", reqEntity); 

Et voila! Vos données de publication contiendront un champ d’image avec le nom de fichier et le chemin d’access sur votre serveur.

Pour télécharger un fichier sur le serveur avec certains parameters en utilisant MultipartUtility de manière simple.

MultipartUtility.java

 public class MultipartUtility { private final Ssortingng boundary; private static final Ssortingng LINE_FEED = "\r\n"; private HttpURLConnection httpConn; private Ssortingng charset; private OutputStream outputStream; private PrintWriter writer; /** * This constructor initializes a new HTTP POST request with content type * is set to multipart/form-data * * @param requestURL * @param charset * @throws IOException */ public MultipartUtility(Ssortingng requestURL, Ssortingng charset) throws IOException { this.charset = charset; // creates a unique boundary based on time stamp boundary = "===" + System.currentTimeMillis() + "==="; URL url = new URL(requestURL); Log.e("URL", "URL : " + requestURL.toSsortingng()); httpConn = (HttpURLConnection) url.openConnection(); httpConn.setUseCaches(false); httpConn.setDoOutput(true); // indicates POST method httpConn.setDoInput(true); httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); httpConn.setRequestProperty("User-Agent", "CodeJava Agent"); httpConn.setRequestProperty("Test", "Bonjour"); outputStream = httpConn.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true); } /** * Adds a form field to the request * * @param name field name * @param value field value */ public void addFormField(Ssortingng name, Ssortingng value) { writer.append("--" + boundary).append(LINE_FEED); writer.append("Content-Disposition: form-data; name=\"" + name + "\"") .append(LINE_FEED); writer.append("Content-Type: text/plain; charset=" + charset).append( LINE_FEED); writer.append(LINE_FEED); writer.append(value).append(LINE_FEED); writer.flush(); } /** * Adds a upload file section to the request * * @param fieldName name atsortingbute in  * @param uploadFile a File to be uploaded * @throws IOException */ public void addFilePart(Ssortingng fieldName, File uploadFile) throws IOException { Ssortingng fileName = uploadFile.getName(); writer.append("--" + boundary).append(LINE_FEED); writer.append( "Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"") .append(LINE_FEED); writer.append( "Content-Type: " + URLConnection.guessContentTypeFromName(fileName)) .append(LINE_FEED); writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED); writer.append(LINE_FEED); writer.flush(); FileInputStream inputStream = new FileInputStream(uploadFile); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); inputStream.close(); writer.append(LINE_FEED); writer.flush(); } /** * Adds a header field to the request. * * @param name - name of the header field * @param value - value of the header field */ public void addHeaderField(Ssortingng name, Ssortingng value) { writer.append(name + ": " + value).append(LINE_FEED); writer.flush(); } /** * Completes the request and receives response from the server. * * @return a list of Ssortingngs as response in case the server returned * status OK, otherwise an exception is thrown. * @throws IOException */ public Ssortingng finish() throws IOException { SsortingngBuffer response = new SsortingngBuffer(); writer.append(LINE_FEED).flush(); writer.append("--" + boundary + "--").append(LINE_FEED); writer.close(); // checks server's status code first int status = httpConn.getResponseCode(); if (status == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader( httpConn.getInputStream())); Ssortingng line = null; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); httpConn.disconnect(); } else { throw new IOException("Server returned non-OK status: " + status); } return response.toSsortingng(); } } 

Pour upload votre file avec les parameters.

REMARQUE: placez ce code ci-dessous dans non-ui-thread pour obtenir une réponse.

 Ssortingng charset = "UTF-8"; Ssortingng requestURL = "YOUR_URL"; MultipartUtility multipart = new MultipartUtility(requestURL, charset); multipart.addFormField("param_name_1", "param_value"); multipart.addFormField("param_name_2", "param_value"); multipart.addFormField("param_name_3", "param_value"); multipart.addFilePart("file_param_1", new File(file_path)); Ssortingng response = multipart.finish(); // response from server. 

La solution de Jaydipsinh Zala n’a pas fonctionné pour moi, mais je ne sais pas pourquoi parce que cela semble trop proche de la solution.

Donc, je fusionne celle-ci avec l’excellente solution et l’explication de Mihai Todor et maintenant cette classe fonctionne pour moi. Si cela aide quelqu’un:

MultipartUtility2V.java

 import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.Files; public class MultipartUtilityV2 { private HttpURLConnection httpConn; private DataOutputStream request; private final Ssortingng boundary = "*****"; private final Ssortingng crlf = "\r\n"; private final Ssortingng twoHyphens = "--"; /** * This constructor initializes a new HTTP POST request with content type * is set to multipart/form-data * * @param requestURL * @throws IOException */ public MultipartUtilityV2(Ssortingng requestURL) throws IOException { // creates a unique boundary based on time stamp URL url = new URL(requestURL); httpConn = (HttpURLConnection) url.openConnection(); httpConn.setUseCaches(false); httpConn.setDoOutput(true); // indicates POST method httpConn.setDoInput(true); httpConn.setRequestMethod("POST"); httpConn.setRequestProperty("Connection", "Keep-Alive"); httpConn.setRequestProperty("Cache-Control", "no-cache"); httpConn.setRequestProperty( "Content-Type", "multipart/form-data;boundary=" + this.boundary); request = new DataOutputStream(httpConn.getOutputStream()); } /** * Adds a form field to the request * * @param name field name * @param value field value */ public void addFormField(Ssortingng name, Ssortingng value)throws IOException { request.writeBytes(this.twoHyphens + this.boundary + this.crlf); request.writeBytes("Content-Disposition: form-data; name=\"" + name + "\""+ this.crlf); request.writeBytes("Content-Type: text/plain; charset=UTF-8" + this.crlf); request.writeBytes(this.crlf); request.writeBytes(value+ this.crlf); request.flush(); } /** * Adds a upload file section to the request * * @param fieldName name atsortingbute in  * @param uploadFile a File to be uploaded * @throws IOException */ public void addFilePart(Ssortingng fieldName, File uploadFile) throws IOException { Ssortingng fileName = uploadFile.getName(); request.writeBytes(this.twoHyphens + this.boundary + this.crlf); request.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\";filename=\"" + fileName + "\"" + this.crlf); request.writeBytes(this.crlf); byte[] bytes = Files.readAllBytes(uploadFile.toPath()); request.write(bytes); } /** * Completes the request and receives response from the server. * * @return a list of Ssortingngs as response in case the server returned * status OK, otherwise an exception is thrown. * @throws IOException */ public Ssortingng finish() throws IOException { Ssortingng response =""; request.writeBytes(this.crlf); request.writeBytes(this.twoHyphens + this.boundary + this.twoHyphens + this.crlf); request.flush(); request.close(); // checks server's status code first int status = httpConn.getResponseCode(); if (status == HttpURLConnection.HTTP_OK) { InputStream responseStream = new BufferedInputStream(httpConn.getInputStream()); BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream)); Ssortingng line = ""; SsortingngBuilder ssortingngBuilder = new SsortingngBuilder(); while ((line = responseStreamReader.readLine()) != null) { ssortingngBuilder.append(line).append("\n"); } responseStreamReader.close(); response = ssortingngBuilder.toSsortingng(); httpConn.disconnect(); } else { throw new IOException("Server returned non-OK status: " + status); } return response; } } 

basé sur la solution de Mihai, si quelqu’un a le problème de sauvegarder des images sur le serveur comme ce qui s’est passé sur mon serveur. changez la partie Bitmap to Bytebuffer en:

 ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG,100,bos); byte[] pixels = bos.toByteArray(); 

Je n’ai pas testé cela, mais vous pourriez essayer d’utiliser PipedInputStream et PipedOutputStream. Cela pourrait ressembler à quelque chose comme:

 final Bitmap bmp = … // your bitmap // Set up Piped streams final PipedOutputStream pos = new PipedOutputStream(new ByteArrayOutputStream()); final PipedInputStream pis = new PipedInputStream(pos); // Send bitmap data to the PipedOutputStream in a separate thread new Thread() { public void run() { bmp.compress(Bitmap.CompressFormat.PNG, 100, pos); } }.start(); // Send POST request try { // Construct InputStreamEntity that feeds off of the PipedInputStream InputStreamEntity reqEntity = new InputStreamEntity(pis, -1); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); reqEntity.setContentType("binary/octet-stream"); reqEntity.setChunked(true); httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); } catch (Exception e) { e.printStackTrace() } 

Cette réponse https://stackoverflow.com/a/33149413/6481542 m’a permis de télécharger 90% de gros fichiers sur un serveur de développement Django, mais j’ai dû utiliser setFixedLengthStreamingMode pour le faire fonctionner. Cela nécessite de définir Content-Length avant d’écrire le contenu, ce qui nécessite une réécriture assez importante de la réponse ci-dessus. Voici mon résultat final

 public class MultipartLargeUtility { private final Ssortingng boundary; private static final Ssortingng LINE_FEED = "\r\n"; private HttpURLConnection httpConn; private Ssortingng charset; private OutputStream outputStream; private PrintWriter writer; private final int maxBufferSize = 4096; private long contentLength = 0; private URL url; private List fields; private List files; private class FormField { public Ssortingng name; public Ssortingng value; public FormField(Ssortingng name, Ssortingng value) { this.name = name; this.value = value; } } private class FilePart { public Ssortingng fieldName; public File uploadFile; public FilePart(Ssortingng fieldName, File uploadFile) { this.fieldName = fieldName; this.uploadFile = uploadFile; } } /** * This constructor initializes a new HTTP POST request with content type * is set to multipart/form-data * * @param requestURL * @param charset * @throws IOException */ public MultipartLargeUtility(Ssortingng requestURL, Ssortingng charset, boolean requireCSRF) throws IOException { this.charset = charset; // creates a unique boundary based on time stamp boundary = "===" + System.currentTimeMillis() + "==="; url = new URL(requestURL); fields = new ArrayList<>(); files = new ArrayList<>(); if (requireCSRF) { getCSRF(); } } /** * Adds a form field to the request * * @param name field name * @param value field value */ public void addFormField(Ssortingng name, Ssortingng value) throws UnsupportedEncodingException { Ssortingng fieldContent = "--" + boundary + LINE_FEED; fieldContent += "Content-Disposition: form-data; name=\"" + name + "\"" + LINE_FEED; fieldContent += "Content-Type: text/plain; charset=" + charset + LINE_FEED; fieldContent += LINE_FEED; fieldContent += value + LINE_FEED; contentLength += fieldContent.getBytes(charset).length; fields.add(new FormField(name, value)); } /** * Adds a upload file section to the request * * @param fieldName name atsortingbute in  * @param uploadFile a File to be uploaded * @throws IOException */ public void addFilePart(Ssortingng fieldName, File uploadFile) throws IOException { Ssortingng fileName = uploadFile.getName(); Ssortingng fieldContent = "--" + boundary + LINE_FEED; fieldContent += "Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"" + LINE_FEED; fieldContent += "Content-Type: " + URLConnection.guessContentTypeFromName(fileName) + LINE_FEED; fieldContent += "Content-Transfer-Encoding: binary" + LINE_FEED; fieldContent += LINE_FEED; // file content would go here fieldContent += LINE_FEED; contentLength += fieldContent.getBytes(charset).length; contentLength += uploadFile.length(); files.add(new FilePart(fieldName, uploadFile)); } /** * Adds a header field to the request. * * @param name - name of the header field * @param value - value of the header field */ //public void addHeaderField(Ssortingng name, Ssortingng value) { // writer.append(name + ": " + value).append(LINE_FEED); // writer.flush(); //} /** * Completes the request and receives response from the server. * * @return a list of Ssortingngs as response in case the server returned * status OK, otherwise an exception is thrown. * @throws IOException */ public List finish() throws IOException { List response = new ArrayList(); Ssortingng content = "--" + boundary + "--" + LINE_FEED; contentLength += content.getBytes(charset).length; if (!openConnection()) { return response; } writeContent(); // checks server's status code first int status = httpConn.getResponseCode(); if (status == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader( httpConn.getInputStream())); Ssortingng line = null; while ((line = reader.readLine()) != null) { response.add(line); } reader.close(); httpConn.disconnect(); } else { throw new IOException("Server returned non-OK status: " + status); } return response; } private boolean getCSRF() throws IOException { /// First, need to get CSRF token from server /// Use GET request to get the token CookieManager cookieManager = new CookieManager(); CookieHandler.setDefault(cookieManager); HttpURLConnection conn = null; conn = (HttpURLConnection) url.openConnection(); conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("GET"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.getContent(); conn.disconnect(); /// parse the returned object for the CSRF token CookieStore cookieJar = cookieManager.getCookieStore(); List cookies = cookieJar.getCookies(); Ssortingng csrf = null; for (HttpCookie cookie : cookies) { Log.d("cookie", "" + cookie); if (cookie.getName().equals("csrftoken")) { csrf = cookie.getValue(); break; } } if (csrf == null) { Log.d(TAG, "Unable to get CSRF"); return false; } Log.d(TAG, "Received cookie: " + csrf); addFormField("csrfmiddlewaretoken", csrf); return true; } private boolean openConnection() throws IOException { httpConn = (HttpURLConnection) url.openConnection(); httpConn.setUseCaches(false); httpConn.setDoOutput(true); // indicates POST method httpConn.setDoInput(true); //httpConn.setRequestProperty("Accept-Encoding", "identity"); httpConn.setFixedLengthStreamingMode(contentLength); httpConn.setRequestProperty("Connection", "Keep-Alive"); httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); outputStream = new BufferedOutputStream(httpConn.getOutputStream()); writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true); return true; } private void writeContent() throws IOException { for (FormField field : fields) { writer.append("--" + boundary).append(LINE_FEED); writer.append("Content-Disposition: form-data; name=\"" + field.name + "\"") .append(LINE_FEED); writer.append("Content-Type: text/plain; charset=" + charset).append( LINE_FEED); writer.append(LINE_FEED); writer.append(field.value).append(LINE_FEED); writer.flush(); } for (FilePart filePart : files) { Ssortingng fileName = filePart.uploadFile.getName(); writer.append("--" + boundary).append(LINE_FEED); writer.append( "Content-Disposition: form-data; name=\"" + filePart.fieldName + "\"; filename=\"" + fileName + "\"") .append(LINE_FEED); writer.append( "Content-Type: " + URLConnection.guessContentTypeFromName(fileName)) .append(LINE_FEED); writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED); writer.append(LINE_FEED); writer.flush(); FileInputStream inputStream = new FileInputStream(filePart.uploadFile); int bufferSize = Math.min(inputStream.available(), maxBufferSize); byte[] buffer = new byte[bufferSize]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer, 0, bufferSize)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); inputStream.close(); writer.append(LINE_FEED); writer.flush(); } writer.append("--" + boundary + "--").append(LINE_FEED); writer.close(); } } 

L’utilisation est en grande partie la même que dans la réponse ci-dessus, mais j’ai inclus le support CSRF que Django utilise par défaut avec des formulaires

 boolean useCSRF = true; MultipartLargeUtility multipart = new MultipartLargeUtility(url, "UTF-8",useCSRF); multipart.addFormField("param1","value"); multipart.addFilePart("filefield",new File("/path/to/file")); List response = multipart.finish(); Log.w(TAG,"SERVER REPLIED:"); for(Ssortingng line : response) { Log.w(TAG, "Upload Files Response:::" + line); } 

Voici ce que j’ai fait pour télécharger une photo en utilisant post request.

 public void uploadFile(int directoryID, Ssortingng filePath) { Bitmap bitmapOrg = BitmapFactory.decodeFile(filePath); ByteArrayOutputStream bao = new ByteArrayOutputStream(); Ssortingng upload_url = BASE_URL + UPLOAD_FILE; bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao); byte[] data = bao.toByteArray(); HttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(upload_url); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); try { // Set Data and Content-type header for the image FileBody fb = new FileBody(new File(filePath), "image/jpeg"); SsortingngBody contentSsortingng = new SsortingngBody(directoryID + ""); entity.addPart("file", fb); entity.addPart("directory_id", contentSsortingng); postRequest.setEntity(entity); HttpResponse response = httpClient.execute(postRequest); // Read the response Ssortingng jsonSsortingng = EntityUtils.toSsortingng(response.getEntity()); Log.e("response after uploading file ", jsonSsortingng); } catch (Exception e) { Log.e("Error in uploadFile", e.getMessage()); } } 

Remarque: ce code nécessite des bibliothèques, donc suivez les instructions ici pour obtenir les bibliothèques.

J’ai trouvé l’utilisation de okHttp beaucoup plus facile car je ne pouvais pas faire fonctionner l’une de ces solutions: https://stackoverflow.com/a/37942387/447549

J’ai essayé les solutions ci-dessus et aucune n’a fonctionné pour moi hors de la boîte.

Cependant http://www.baeldung.com/httpclient-post-http-request . Ligne 6 POST Multipart Request traitée en quelques secondes

 public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://www.example.com"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("username", "John"); builder.addTextBody("password", "pass"); builder.addBinaryBody("file", new File("test.txt"), ContentType.APPLICATION_OCTET_STREAM, "file.ext"); HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); CloseableHttpResponse response = client.execute(httpPost); client.close(); }