Upload POST file using HttpURLConnection
suggest changeQuite often it’s necessary to send/upload a file to a remote server, for example, an image, video, audio or a backup of the application database to a remote private server. Assuming the server is expecting a POST request with the content, here’s a simple example of how to complete this task in Android.
File uploads are sent using multipart/form-data POST requests. It’s very easy to implement:
URL url = new URL(postTarget);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
String auth = "Bearer " + oauthToken;
connection.setRequestProperty("Authorization", auth);
String boundary = UUID.randomUUID().toString();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream request = new DataOutputStream(connection.getOutputStream());
request.writeBytes("--" + boundary + "\r\n");
request.writeBytes("Content-Disposition: form-data; name=\"description\"\r\n\r\n");
request.writeBytes(fileDescription + "\r\n");
request.writeBytes("--" + boundary + "\r\n");
request.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n\r\n");
request.write(FileUtils.readFileToByteArray(file));
request.writeBytes("\r\n");
request.writeBytes("--" + boundary + "--\r\n");
request.flush();
int respCode = connection.getResponseCode();
switch(respCode) {
case 200:
//all went ok - read response
break;
case 301:
case 302:
case 307:
//handle redirect - for example, re-post to the new location
break;
default:
//do something sensible
}
Of course, exceptions will need to be caught or declared as being thrown. A couple of points to note about this code:
postTargetis the destination URL of the POST;oauthTokenis the authentication token;fileDescriptionis the description of the file, which is sent as the value of fielddescription;fileis the file to be sent - it’s of typejava.io.File- if you have the file path, you can usenew File(filePath)instead.- It sets the
Authorizationheader to a Bearer token. - It uses Apache Commons IO
FileUtilsto read the file into a byte array. If you already have the content of the file in a byte array, or otherwise in memory, then there is no need to read it.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents