Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save damianmcdonald/b720d9798e0d84092bbd to your computer and use it in GitHub Desktop.
Save damianmcdonald/b720d9798e0d84092bbd to your computer and use it in GitHub Desktop.
Multi Part Upload using Apache HttpClient 4
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
public class ApacheHttpClientMultiPartUpload {
public void exampleMultiPartUpload(File fileToUpload) throws IOException {
final String API_URI = "http://localhost:8080/upload/file";
final HttpClient client = HttpClientBuilder.create().build();
final HttpPost post = new HttpPost(API_URI);
// some json to send to the server as an element of the multi part request
final JSONObject jsonToSend = new JSONObject();
jsonToSend.put("character", "Jabba the Hutt");
jsonToSend.put("movie", "Return of the Jedi");
jsonToSend.put("isGoodGuy", false);
/* create the MultiPartRequest with:
* Text field called "description"
* JSON field called "characterProfile"
* Text field called "filename"
* Binary body part called "file"
*/
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("file", fileToUpload, ContentType.DEFAULT_BINARY, fileToUpload.getName());
builder.addTextBody("filename", fileToUpload.getName(), ContentType.TEXT_PLAIN);
builder.addTextBody("description", "Picture of Jabba the Hutt", ContentType.TEXT_PLAIN);
builder.addTextBody("characterProfile", jsonToSend.toString(), ContentType.APPLICATION_JSON);
final HttpEntity entity = builder.build();
post.setEntity(entity);
final HttpResponse response = client.execute(post);
System.out.println("INFO >>> Response from API was: " + response.toString());
}
}
<!-- dependencies required for this Gist -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5</version>
</dependency>
@sheilambadi
Copy link

Thanks. This was really helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment