Add responseBody field to InvalidResponseCodeException

Issue #6853

Previously the body of an HTTP response was not included in an
InvalidResponseCodeException. This change adds a field to store
the response body, and updates DefaultHttpDataSource to populate
this value.
This commit is contained in:
Fillmore, Christopher 2020-01-10 12:00:59 -05:00
parent 7a849e11f7
commit d94a40ac77
2 changed files with 27 additions and 1 deletions

View File

@ -306,6 +306,11 @@ public interface HttpDataSource extends DataSource {
*/
public final Map<String, List<String>> headerFields;
/**
* The response body, if one was provided.
*/
@Nullable public final byte[] responseBody;
/** @deprecated Use {@link #InvalidResponseCodeException(int, String, Map, DataSpec)}. */
@Deprecated
public InvalidResponseCodeException(
@ -313,15 +318,27 @@ public interface HttpDataSource extends DataSource {
this(responseCode, /* responseMessage= */ null, headerFields, dataSpec);
}
/** @deprecated Use {@link #InvalidResponseCodeException(int, String, Map, DataSpec byte[])}. */
@Deprecated
public InvalidResponseCodeException(
int responseCode,
@Nullable String responseMessage,
Map<String, List<String>> headerFields,
DataSpec dataSpec) {
this(responseCode, responseMessage, headerFields, dataSpec, /* responseBody= */ null);
}
public InvalidResponseCodeException(
int responseCode,
@Nullable String responseMessage,
Map<String, List<String>> headerFields,
DataSpec dataSpec,
@Nullable byte[] responseBody) {
super("Response code: " + responseCode, dataSpec, TYPE_OPEN);
this.responseCode = responseCode;
this.responseMessage = responseMessage;
this.headerFields = headerFields;
this.responseBody = responseBody;
}
}

View File

@ -284,9 +284,16 @@ public class DefaultHttpDataSource extends BaseDataSource implements HttpDataSou
}
String responseMessage;
byte[] errorResponseBody = null;
try {
responseCode = connection.getResponseCode();
responseMessage = connection.getResponseMessage();
InputStream errorStream = connection.getErrorStream();
// Android Studio says errorStream will never be null, but Android docs say otherwise.
// Just check to be sure.
if (errorStream != null) {
errorResponseBody = Util.toByteArray(errorStream);
}
} catch (IOException e) {
closeConnectionQuietly();
throw new HttpDataSourceException("Unable to connect to " + dataSpec.uri.toString(), e,
@ -298,7 +305,9 @@ public class DefaultHttpDataSource extends BaseDataSource implements HttpDataSou
Map<String, List<String>> headers = connection.getHeaderFields();
closeConnectionQuietly();
InvalidResponseCodeException exception =
new InvalidResponseCodeException(responseCode, responseMessage, headers, dataSpec);
new InvalidResponseCodeException(responseCode, responseMessage, headers, dataSpec,
errorResponseBody);
if (responseCode == 416) {
exception.initCause(new DataSourceException(DataSourceException.POSITION_OUT_OF_RANGE));
}