I am a passionate software developer and consultant on Java and related technologies since 2002. I have keen interest in reading, writing tech blogs and designing enterprise applications in Java. Upendra is a DZone MVB and is not an employee of DZone and has posted 5 posts at DZone. You can read more from them at their website. View Full User Profile

File upload With Apache HttpClient Library

  • submit to reddit

File Upload or Attachments are common in most of applications. In this tip, I will show how to perform file uploads using Apache HttpClient version 4.1.3. You can download it at http://hc.apache.org/downloads.cgi

With normal requests, we send multiple parameters to the server by setting a request entity(usually URLEncodedFormEntity) to the http reqeust. For file upload or attachments we need to set a multi-part request entity to the http request. With this MultipartEntity, we would be able to send the usual form parameters and as well as the file content. The following code snippet shows how to do this.

package com.acc.blogs.httpclient;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
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;
public class SampleFileUpload {
     * A generic method to execute any type of Http Request and constructs a response object
     * @param requestBase the request that needs to be exeuted
     * @return server response as <code>String</code>
    private static String executeRequest(HttpRequestBase requestBase){
        String responseString = "" ;
        InputStream responseStream = null ;
        HttpClient client = new DefaultHttpClient () ;
            HttpResponse response = client.execute(requestBase) ;
            if (response != null){
                HttpEntity responseEntity = response.getEntity() ;
                if (responseEntity != null){
                    responseStream = responseEntity.getContent() ;
                    if (responseStream != null){
                        BufferedReader br = new BufferedReader (new InputStreamReader (responseStream)) ;
                        String responseLine = br.readLine() ;
                        String tempResponseString = "" ;
                        while (responseLine != null){
                            tempResponseString = tempResponseString + responseLine + System.getProperty("line.separator") ;
                            responseLine = br.readLine() ;
                        br.close() ;
                        if (tempResponseString.length() > 0){
                            responseString = tempResponseString ;
        } catch (UnsupportedEncodingException e) {
        } catch (ClientProtocolException e) {
        } catch (IllegalStateException e) {
        } catch (IOException e) {
            if (responseStream != null){
                try {
                    responseStream.close() ;
                } catch (IOException e) {
        client.getConnectionManager().shutdown() ;
        return responseString ;
     * Method that builds the multi-part form data request
     * @param urlString the urlString to which the file needs to be uploaded
     * @param file the actual file instance that needs to be uploaded
     * @param fileName name of the file, just to show how to add the usual form parameters
     * @param fileDescription some description for the file, just to show how to add the usual form parameters
     * @return server response as <code>String</code>
    public String executeMultiPartRequest(String urlString, File file, String fileName, String fileDescription) {
        HttpPost postRequest = new HttpPost (urlString) ;
            MultipartEntity multiPartEntity = new MultipartEntity () ;
            //The usual form parameters can be added this way
            multiPartEntity.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : "")) ;
            multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName())) ;
            /*Need to construct a FileBody with the file that needs to be attached and specify the mime type of the file. Add the fileBody to the request as an another part.
            This part will be considered as file part and the rest of them as usual form-data parts*/
            FileBody fileBody = new FileBody(file, "application/octect-stream") ;
            multiPartEntity.addPart("attachment", fileBody) ;
            postRequest.setEntity(multiPartEntity) ;
        }catch (UnsupportedEncodingException ex){
            ex.printStackTrace() ;
        return executeRequest (postRequest) ;
    public static void main(String args[]){
        SampleFileUpload fileUpload = new SampleFileUpload () ;
        File file = new File ("Hydrangeas.jpg") ;
        String response = fileUpload.executeMultiPartRequest("<Request URL>", file, file.getName(), "File Upload test Hydrangeas.jpg description") ;
        System.out.println("Response : "+response);

Make sure you have added all the required HttpClient libraries to the classpath before executing this snippet. Also, change the request URI to point to your server URL.

Hope this would save some of your quality time.


Published at DZone with permission of Upendra Chintala, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)