indiWiz.com

Subhash's Tech Log

Multi-part content upload in Apache Http Components / Http Client

with 3 comments

Apache Http Components project hosts an excellent library for making HTTP client requests. This is a simple example for making multipart/form-data request.

Dependencies to be added to you Maven project:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.0-beta2</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.0-beta2</version>
</dependency>

And finally the code to execute the request:

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

...

// The input:
File f = ...;
String title = ...;
String desc = ...;

// The execution:
DefaultHttpClient httpclient = new DefaultHttpClient();

HttpPost method = new HttpPost("http://host:port/path");
MultipartEntity entity = new MultipartEntity();
entity.addPart("title", new StringBody(title, Charset.forName("UTF-8")));
entity.addPart("desc", new StringBody(desc, Charset.forName("UTF-8")));
FileBody fileBody = new FileBody(f);
entity.addPart("file", fileBody);
method.setEntity(entity);

HttpResponse response = httpclient.execute(method);
System.out.println(response.getStatusLine());

Written by Subhash Chandran

February 11th, 2009 at 9:29 pm

Posted in Java

Tagged with , ,

3 Responses to 'Multi-part content upload in Apache Http Components / Http Client'

Subscribe to comments with RSS or TrackBack to 'Multi-part content upload in Apache Http Components / Http Client'.

  1. At the end I got an example of the Multipart using with the HttpClient4.0!!!
    Thanks!
    Anyway, there is one more dependence to the code:
    The Apache James Mime4j http://james.apache.org/mime4j/index.html (or my Eclipse asks it when using the “entity.addPart()” function)…

    Thanks again :D

    Luc

    5 Nov 09 at 1:48 pm

  2. Finally I found a piece of code working for Http 4 multipart request.

    Thanks man for the effors and time.

    Imran

    Imran Lakhani

    22 Apr 10 at 12:10 pm

  3. Hi, thanks for a nice working code. Is it possible to use file content directly instead of FileBody fileBody = new FileBody(f);

    where f is a File object I have the contents of a xml file in a String variable. Can it be given as a multipart request?

    Abhishek Simon

    18 May 12 at 12:09 pm

Leave a Reply