HttpResponse initialResponse = executeUploadInitiation(initiationRequestUrl);
if (!initialResponse.isSuccessStatusCode()) {
// If the initiation request is not successful return it immediately.
return initialResponse;
}
GenericUrl uploadUrl;
try {
uploadUrl = new GenericUrl(initialResponse.getHeaders().getLocation());
} finally {
initialResponse.disconnect();
}
// Convert media content into a byte stream to upload in chunks.
contentInputStream = mediaContent.getInputStream();
if (!contentInputStream.markSupported() && isMediaLengthKnown()) {
// If we know the media content length then wrap the stream into a Buffered input stream to
// support the {@link InputStream#mark} and {@link InputStream#reset} methods required for
// handling server errors.
contentInputStream = new BufferedInputStream(contentInputStream);
}
HttpResponse response;
// Upload the media content in chunks.
while (true) {
currentRequest = requestFactory.buildPutRequest(uploadUrl, null);
setContentAndHeadersOnCurrentRequest();
if (backOffPolicyEnabled) {
// use exponential back-off on server error
currentRequest.setBackOffPolicy(new MediaUploadExponentialBackOffPolicy(this));
} else {
// set mediaErrorHandler as I/O exception handler and as unsuccessful response handler for
// calling to serverErrorCallback on an I/O exception or an abnormal HTTP response
new MediaUploadErrorHandler(this, currentRequest);
}
if (isMediaLengthKnown()) {
// TODO(rmistry): Support gzipping content for the case where media content length is
// known (https://code.google.com/p/google-api-java-client/issues/detail?id=691).
} else if (!disableGZipContent) {
currentRequest.setEncoding(new GZipEncoding());
}
response = executeCurrentRequest(currentRequest);
boolean returningResponse = false;
try {
if (response.isSuccessStatusCode()) {
totalBytesServerReceived = getMediaContentLength();
if (mediaContent.getCloseInputStream()) {
contentInputStream.close();
}
updateStateAndNotifyListener(UploadState.MEDIA_COMPLETE);
returningResponse = true;
return response;
}
if (response.getStatusCode() != 308) {
returningResponse = true;
return response;
}
// Check to see if the upload URL has changed on the server.
String updatedUploadUrl = response.getHeaders().getLocation();
if (updatedUploadUrl != null) {
uploadUrl = new GenericUrl(updatedUploadUrl);
}
// we check the amount of bytes the server received so far, because the server may process
// fewer bytes than the amount of bytes the client had sent
long newBytesServerReceived = getNextByteIndex(response.getHeaders().getRange());