Multipart requests using Httpclient api

In this blog I'll describe how to use the httpclient api in order to issue multi part post requests and also how to process the request on the server side. Hopefully, it'll save others the time I spent to get this working.

Here are the core libraries I used.

Apache Commons FileUpload 1.2.1
Apache HttpClient 4.2.1 (which includes httpmime-4.1.2.jar)

Creating a multipart post request:

    public void postMultipartMessage() throws ClientProtocolException, IOException
    {
            HttpPost postRequest = new HttpPost("http://host:port/webapp/servlet");
           
            MultipartEntity reqEntity = new MultipartEntity();
            

            //Add a string parameter
            StringBody strBody = new StringBody("string parameter");
            reqEntity.addPart("string", strBody);
            

            //Add a file attachment
            FileBody fileBody = new FileBody(new File("/file/path"));
            reqEntity.addPart("file", fileBody);
           
            postRequest.setEntity(reqEntity);

            HttpContext httpContext = new BasicHttpContext();
            HttpResponse response = getHttpClient().execute(postRequest, httpContext);

            //getHttpClient() initializes the http client object perhaps from a properties file
    }


This could also have been done by submitting a multipart http request using a jsp presented to a user but the idea here is to show how this can be done programatically between two servers with no end user involved.   
   
Processing a multipart post request on the server side:


    public void processMultipartMessage(HttpServletRequest request) throws FileUploadException, IOException
    {
        if(request.getMethod().equals(URIConstants.HTTP_METHOD.POST.toString()))
        {
            if(request.getContentType().toUpperCase().contains("MULTIPART"))
            {
                List<FileItem> items = 

                  new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
                for (FileItem item : items)
                {
                    if (item.isFormField())
                    {
                        // Retrieve form field
                        String fieldname = item.getFieldName();
                        String fieldvalue = item.getString();
                        // do whatever needs to be done with form field..
                    }
                    else
                    {
                        // Process form file field (input type="file").
                        String filename = FilenameUtils.getName(item.getName());
                        InputStream filecontent = item.getInputStream();
                        // do whatever needs to be done with form file field..
                    }
                }
            }
        }
    }