This technique is not optimized for Android and will likely run poorly. The convention is to use AndroidHttpClient:
Subclass of the Apache DefaultHttpClient that is configured with reasonable default settings and registered schemes for Android, and also lets the user add HttpRequestInterceptor classes.
If you really want to use Sun's code above, you should be careful because you will likely exceed the VM heap budget when the size of the file exceeds the amount of heap space available to the application.
It would be wise to first check if there is sufficient heap space left using ActivityManager. See also the elaborate answer to this question.
Edit:
I've found an example of sending an InputStream via POST. Here a file is being read from a resource (res/data.xml
), but you could replace the InputStream
with the FileInputStream
from your snippet. Converting the InputStream
to a byte array does essentially the same as your code: read the entire file into memory and push it into the request. This is a notorious cause of OutOfMemoryError
s, so take care that you don't read files that are too large (I would suggest less than 1 MB).
public void executeMultipartPost() throws Exception {
try {
InputStream is = this.getAssets().open("data.xml");
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://w3mentor.com/Upload.aspx");
byte[] data = IOUtils.toByteArray(is);
InputStreamBody isb = new InputStreamBody(new ByteArrayInputStream(data),"uploadedFile");
StringBody sb1 = new StringBody("someTextGoesHere");
StringBody sb2 = new StringBody("someTextGoesHere too");
MultipartEntity multipartContent = new MultipartEntity();
multipartContent.addPart("uploadedFile", isb);
multipartContent.addPart("one", sb1);
multipartContent.addPart("two", sb2);
postRequest.setEntity(multipartContent);
HttpResponse res = httpClient.execute(postRequest);
res.getEntity().getContent().close();
} catch (Throwable e) {
// handle exception here
}
}