Blog : File upload With Apache HttpClient Library
File upload With Apache HttpClient Library
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;
002.
003.import java.io.BufferedReader;
004.import java.io.File;
005.import java.io.IOException;
006.import java.io.InputStream;
007.import java.io.InputStreamReader;
008.import java.io.UnsupportedEncodingException;
009.
010.import org.apache.http.HttpEntity;
011.import org.apache.http.HttpResponse;
012.import org.apache.http.client.ClientProtocolException;
013.import org.apache.http.client.HttpClient;
014.import org.apache.http.client.methods.HttpPost;
015.import org.apache.http.client.methods.HttpRequestBase;
016.import org.apache.http.entity.mime.MultipartEntity;
017.import org.apache.http.entity.mime.content.FileBody;
018.import org.apache.http.entity.mime.content.StringBody;
019.import org.apache.http.impl.client.DefaultHttpClient;
020.
021.public class SampleFileUpload {
022.
023./**
024.* A generic method to execute any type of Http Request and constructs a response object
025.* @param requestBase the request that needs to be exeuted
026.* @return server response as String
027.*/
028.private static String executeRequest(HttpRequestBase requestBase){
029.String responseString = "" ;
030.
031.InputStream responseStream = null ;
032.HttpClient client = new DefaultHttpClient () ;
033.try{
034.HttpResponse response = client.execute(requestBase) ;
035.if (response != null){
036.HttpEntity responseEntity = response.getEntity() ;
037.
038.if (responseEntity != null){
039.responseStream = responseEntity.getContent() ;
040.if (responseStream != null){
041.BufferedReader br = new BufferedReader (new InputStreamReader (responseStream)) ;
042.String responseLine = br.readLine() ;
043.String tempResponseString = "" ;
044.while (responseLine != null){
045.tempResponseString = tempResponseString + responseLine + System.getProperty("line.separator") ;
046.responseLine = br.readLine() ;
047.}
048.br.close() ;
049.if (tempResponseString.length() > 0){
050.responseString = tempResponseString ;
051.}
052.}
053.}
054.}
055.} catch (UnsupportedEncodingException e) {
056.e.printStackTrace();
057.} catch (ClientProtocolException e) {
058.e.printStackTrace();
059.} catch (IllegalStateException e) {
060.e.printStackTrace();
061.} catch (IOException e) {
062.e.printStackTrace();
063.}finally{
064.if (responseStream != null){
065.try {
066.responseStream.close() ;
067.} catch (IOException e) {
068.e.printStackTrace();
069.}
070.}
071.}
072.client.getConnectionManager().shutdown() ;
073.
074.return responseString ;
075.}
076.
077./**
078.* Method that builds the multi-part form data request
079.* @param urlString the urlString to which the file needs to be uploaded
080.* @param file the actual file instance that needs to be uploaded
081.* @param fileName name of the file, just to show how to add the usual form parameters
082.* @param fileDescription some description for the file, just to show how to add the usual form parameters
083.* @return server response as String
084.*/
085.public String executeMultiPartRequest(String urlString, File file, String fileName, String fileDescription) {
086.
087.HttpPost postRequest = new HttpPost (urlString) ;
088.try{
089.
090.MultipartEntity multiPartEntity = new MultipartEntity () ;
091.
092.//The usual form parameters can be added this way
093.multiPartEntity.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : "")) ;
094.multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName())) ;
095.
096./*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.
097.This part will be considered as file part and the rest of them as usual form-data parts*/
098.FileBody fileBody = new FileBody(file, "application/octect-stream") ;
099.multiPartEntity.addPart("attachment", fileBody) ;
100.
101.postRequest.setEntity(multiPartEntity) ;
102.}catch (UnsupportedEncodingException ex){
103.ex.printStackTrace() ;
104.}
105.
106.return executeRequest (postRequest) ;
107.}
108.
109.public static void main(String args[]){
110.SampleFileUpload fileUpload = new SampleFileUpload () ;
111.File file = new File ("Hydrangeas.jpg") ;
112.
113.String response = fileUpload.executeMultiPartRequest("", file, file.getName(),"File Upload test Hydrangeas.jpg description") ;
114.System.out.println("Response : "+response);
115.}
116.
117.}