HTTP POST (multipart/form-data) on Android


Since the coming of cloud computing, sometimes we would like to let the Android application send HTTP POST request to a server and get result back from the server. Especially, we would like to do HTTP POST which includes multipart form data (file and variables). This post is going to show you how to do this.

Assume the data to be posted contains a file whose name is uploadedFile, a variable whose name is to, and a variable whose name is from. The following is the code snippet for posting the data to the server:

http-post-multipart-form-data-on-android.java | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/* set the variable needed by http post */
private String uploadFile="/sdcard/test.png";
private String actionUrl = "http://your_domain/your_post_url";
final String end = "\r\n";
final String twoHyphens = "--";
final String boundary = "*****++++++************++++++++++++";

URL url = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();

conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");

/* setRequestProperty */
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+ boundary);

DataOutputStream ds = new DataOutputStream(conn.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; name=\"from\""+end+end+"auto"+end);
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; name=\"to\""+end+end+"ja"+end);
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; name=\"uploadedFile\";filename=\"" + uploadFile +"\"" + end);
ds.writeBytes(end);

FileInputStream fStream = new FileInputStream(uploadFile);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;

while((length = fStream.read(buffer)) != -1) {
  ds.write(buffer, 0, length);
}
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
/* close streams */
fStream.close();
ds.flush();
ds.close();

if(conn.getResponseCode() != HttpURLConnection.HTTP_OK){
  Toast.makeText(getBaseContext(), conn.getResponseMessage(), Toast.LENGTH_LONG);
}

StringBuffer b = new StringBuffer();
InputStream is = conn.getInputStream();
byte[] data = new byte[bufferSize];
int leng = -1;
while((leng = is.read(data)) != -1) {
  b.append(new String(data, 0, leng));
}
String result = b.toString();

Hope this example would be helpful for those who are interested!