Upload POST file using HttpURLConnection

suggest change

Quite 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:

  1. postTarget is the destination URL of the POST; oauthToken is the authentication token; fileDescription is the description of the file, which is sent as the value of field description; file is the file to be sent - it’s of type java.io.File - if you have the file path, you can use new File(filePath) instead.
  2. It sets the Authorization header to a Bearer token.
  3. It uses Apache Commons IO FileUtils to 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents