Archive for the ‘http’ tag
Forcing HTTP Download
To force HTTP download of a dynamically generated content, I usually set the HTTP header Content-Type to application/octet-stream. This forces the browser to display the Save dialog box. But this has the limitation of sending the wrong content-type even when we know the correct one. Recently I discovered another HTTP header which solves this problem. This is the Content-Disposition header. This can take following two vales:
- inline: This will render the content inline in the browser.
- attachment: This will force the browser to display the Save dialog.
When generating dynamic content, it is also recommended to specify proper filename. This file name can also be specified as a parameter to Content-Disposition header. An example:
Content-Disposition: attachment;filename=document.pdf
Content-Disposition is covered in RFC 2183.
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());