2 Minutes To Code (β Version)

Apache Commons Http Client - 2 minute tutorial

Uploading file : How to upload a file to an http webserver

This example shows how to upload a file to an http server.

The operating code here is the method setRequestEntity(...) of PostMethod class and passing the org.apache.commons.httpclient.methods.multipart.FilePart objects pointing to the file to be uploaded.
package com.techfundaes.httpBag;

import java.io.File;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;

public class SimplePostToUploadFile
{
	public static void main(String[] args)
	{
		HttpClient httpClient = new HttpClient();
		PostMethod postMethod = new PostMethod("anxmas"); 
		try
		{
			File fileToUpload = new File("./partyPic.jpg");
			Part[] parts = new Part[1];
			parts[0] =  new FilePart(fileToUpload.getName(), fileToUpload);
			postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
			httpClient.executeMethod(postMethod);
			System.out.println("responseString:"+postMethod.getResponseBodyAsString());
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			postMethod.releaseConnection();
		}
	}
}