Skip to content

Instantly share code, notes, and snippets.

@twaddington
Created November 8, 2011 01:18
Show Gist options
  • Save twaddington/1346744 to your computer and use it in GitHub Desktop.
Save twaddington/1346744 to your computer and use it in GitHub Desktop.
Simple method to parse an HttpResponse for a Content-Range header and extract the instance length (total size). Great for making partial-content requests.
/**
* <p>This method checks an HttpResponse for a Content-Range
* header and, if present, attempts to parse the instance-length
* from the header value.</p>
* <p>{@link http://tools.ietf.org/html/rfc2616#section-14.16}</p>
*
* @param response
* @return the total number of bytes for the instance, or a negative number if unknown.
*/
public static long getInstanceLength(HttpResponse response) {
long length = -1;
if (response != null) {
Header[] range = response.getHeaders("Content-Range");
if (range.length > 0) {
// Get the header value
String value = range[0].getValue();
// Split the value
String[] section = value.split("/");
try {
// Parse for the instance length
length = Long.parseLong(section[1]);
} catch (NumberFormatException e) {
// The server returned an unknown "*" or invalid instance-length
Log.d(TAG, String.format("The HttpResponse contains an invalid instance-length: %s", value));
}
}
}
return length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment