+ // The actual network request is in a `try` bracket so that `disconnect()` is run in the `finally` section even if an error is encountered in the main block.
+ try {
+ // Get the status code. This initiates a network connection.
+ int responseCode = httpUrlConnection.getResponseCode();
+
+ // Check the response code.
+ if (responseCode >= 400) { // The response code is an error message.
+ // Set the formatted file size to indicate a bad URL.
+ formattedFileSize = context.getString(R.string.invalid_url);
+
+ // Set the file name according to the URL.
+ fileNameString = getFileNameFromUrl(context, urlString, null);
+ } else { // The response code is not an error message.
+ // Get the headers.
+ String contentLengthString = httpUrlConnection.getHeaderField("Content-Length");
+ String contentDispositionString = httpUrlConnection.getHeaderField("Content-Disposition");
+ String contentTypeString = httpUrlConnection.getContentType();
+
+ // Remove anything after the MIME type in the content type string.
+ if (contentTypeString.contains(";")) {
+ // Remove everything beginning with the `;`.
+ contentTypeString = contentTypeString.substring(0, contentTypeString.indexOf(";"));
+ }
+
+ // Only process the content length string if it isn't null.
+ if (contentLengthString != null) {
+ // Convert the content length string to a long.
+ long fileSize = Long.parseLong(contentLengthString);
+
+ // Format the file size.
+ formattedFileSize = NumberFormat.getInstance().format(fileSize) + " " + context.getString(R.string.bytes);
+ }
+
+ // Get the file name string from the content disposition.
+ fileNameString = getFileNameFromHeaders(context, contentDispositionString, contentTypeString, urlString);
+ }
+ } finally {
+ // Disconnect the HTTP URL connection.
+ httpUrlConnection.disconnect();