Site icon

Multipart file upload client for RESTFul web service (java/ example /httpclient)

Multipart file upload client:

What is objective of File Upload client?

We have discussed about the RESTFul multipart web service  using spring framework. We have tested the Multipart file upload client with RESTFul multipart web service . We can down the web service project from above link to check the end to end flow of applications. We have used “http://localhost:9095/multipart/file/upload” (we will discuss shortly) to upload files to web service. Where “/multipart” defines the context path, where web service is is being deployed. We can change the above url as per our web service deployment.

File upload client will use  Apache HttpClient, to upload multipart files to RESTFul multipart web service. We will make use of MultipartEntityBuilder class to create multipart content.

Maven dependencies for apache httpclient

<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>
<dependency>
	<groupId>commons-codec</groupId>
	<artifactId>commons-codec</artifactId>
	<version>1.10</version>
</dependency>
<dependency>
	<groupId>commons-logging</groupId>
	<artifactId>commons-logging</artifactId>
	<version>1.2</version>
</dependency>

Program – Multipart file upload client of RESTFul web service (httpclient/ java)

1.) FileUploadClient class:

FileUploadClient is capable of uploading multipart contents to REST web service using HttpClient.

  1. Create multipart entity builder
  2. Add multipart contents like image, pdf, text etc.
  3. Create HttpClient to upload multi part contents
  4. Execute post request to invoke RESTFul resource.
  5. Parse the response and display the execution result.
package org.learn.FileUpload;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

public class FileUploadClient {
	public static void fileUpload(String url, File imgFile,
			File pdfFile, File jsonFile, InputStream zipFile) {
		CloseableHttpClient httpclient = null;
		try {
			//Enter your host and port number...
			HttpPost post = new HttpPost(url);
			post.addHeader("Content-Type","multipart/mixed; boundary=\"---Content Boundary\"");
			//path of local file and correct for rest of the files also
			
			String message = "This is a multipart post";
			// Create Multipart instance
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
			// Add image file to upload
			builder.addBinaryBody("imgFile", imgFile,
					ContentType.DEFAULT_BINARY, imgFile.getName());
			builder.setBoundary("---Content Boundary");
			
			// Add pdf file to upload
			builder.addBinaryBody("pdfFile", pdfFile,
					ContentType.create("application/pdf"),
					pdfFile.getName());
			builder.setBoundary("---Content Boundary");
			
			// Add json file to upload
			builder.addBinaryBody("jsonFile", jsonFile,
					ContentType.APPLICATION_JSON, jsonFile.getName());
			builder.setBoundary("---Content Boundary");
			// Add zip file upload
			builder.addBinaryBody("zipFile", zipFile,
					ContentType.create("application/zip"), "SoftwareData.rar");
			builder.setBoundary("---Content Boundary");
			builder.addTextBody("textMessage", message, ContentType.TEXT_PLAIN);
			builder.setBoundary("---Content Boundary");

			httpclient = HttpClientBuilder.create().build();
			HttpEntity entity = builder.build();
			post.setEntity(entity);
			// execute the post request
			HttpResponse response = httpclient.execute(post);
			// Read the response HTML
			if (response != null) {
				HttpEntity responseEntity = response.getEntity();
				if (responseEntity != null) {
					// Read the response string if required
					InputStream 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){
                            System.out.println(tempResponseString);
                        }
                    }
                    responseStream.close();
				}
			}
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return;
	}	
}

2.) Application Class

Application class contains the main method. Application class performs following operation:

package org.learn.FileUpload;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class Application {
	public static void main(String[] args) {
		try {
			String url = "http://localhost:9095/multipart/file/upload";
			File imgFile = new File("src/main/resource/img.jpg");
			File pdfFile = new File("src/main/resource/SamplePdf.pdf");
			File jsonFile = new File("src/main/resource/Organization.json");
			InputStream zipFile = new FileInputStream("src/main/resource/SoftwareData.rar");
			
			FileUploadClient.fileUpload(
					url,imgFile,pdfFile,
					jsonFile,zipFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output – Multipart file upload client of RESTFul web service (httpclient/ java)

uploaded files :[img.jpg, SamplePdf.pdf, Organization.json, SoftwareData.rar]

Download Code – Multipart file upload apache httpclient

 

Exit mobile version