Archive for the ‘httpclient’ tag
Multi-part content upload in Apache Http Components / Http Client
Apache Http Components project hosts an excellent library for making HTTP client requests. This is a simple example for making multipart/form-data request.
Dependencies to be added to you Maven project:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.0-beta2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.0-beta2</version>
</dependency>
And finally the code to execute the request:
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpPost;
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;
...
// The input:
File f = ...;
String title = ...;
String desc = ...;
// The execution:
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost method = new HttpPost("http://host:port/path");
MultipartEntity entity = new MultipartEntity();
entity.addPart("title", new StringBody(title, Charset.forName("UTF-8")));
entity.addPart("desc", new StringBody(desc, Charset.forName("UTF-8")));
FileBody fileBody = new FileBody(f);
entity.addPart("file", fileBody);
method.setEntity(entity);
HttpResponse response = httpclient.execute(method);
System.out.println(response.getStatusLine());