La API de Campaign Manager 360 te permite descargar archivos de informes, que son el resultado de ejecutar un informe del Creador de informes. También permite proporcionarles a los usuarios acceso directo a un archivo a través de un vínculo.
Según el tipo de descarga que desees realizar, utilizarás uno de los siguientes enfoques:
- Descarga directa: Files.get con el parámetro
alt=media
- Descarga archivos en un navegador:
browserUrl
desde el recurso Archivos.
El resto de esta guía proporciona instrucciones detalladas para realizar estos tipos de descargas a través del recurso Archivos.
Requisitos previos
Para descargar un archivo, necesitarás algunos datos:
- El ID del informe al que pertenece el archivo. Para ello, cree un informe nuevo o busque uno existente.
- El ID del archivo que se descargará. Para ello, ejecuta el informe del paso anterior o consulta la lista de archivos existentes, como se muestra en el siguiente ejemplo:
C#
File target = null;
FileList files;
String nextPageToken = null;
do {
// Create and execute the files list request.
ReportsResource.FilesResource.ListRequest request =
service.Reports.Files.List(profileId, reportId);
request.PageToken = nextPageToken;
files = request.Execute();
foreach (File file in files.Items) {
if (IsTargetFile(file)) {
target = file;
break;
}
}
// Update the next page token.
nextPageToken = files.NextPageToken;
} while (target == null
&& files.Items.Any()
&& !String.IsNullOrEmpty(nextPageToken));
Java
File target = null;
FileList files;
String nextPageToken = null;
do {
// Create and execute the files list request.
files = reporting.reports().files().list(profileId, reportId).setPageToken(nextPageToken)
.execute();
for (File file : files.getItems()) {
if (isTargetFile(file)) {
target = file;
break;
}
}
// Update the next page token.
nextPageToken = files.getNextPageToken();
} while (target == null
&& !files.getItems().isEmpty()
&& !Strings.isNullOrEmpty(nextPageToken));
PHP
$target = null;
$response = null;
$pageToken = null;
do {
// Create and execute the file list request.
$response = $this->service->reports_files->listReportsFiles(
$userProfileId,
$reportId,
['pageToken' => $pageToken]
);
foreach ($response->getItems() as $file) {
if ($this->isTargetFile($file)) {
$target = $file;
break;
}
}
$pageToken = $response->getNextPageToken();
} while (empty($target) && !empty($response->getItems()) && !empty($pageToken));
Python
target = None
request = service.reports().files().list(
profileId=profile_id, reportId=report_id)
while True:
response = request.execute()
for report_file in response['items']:
if is_target_file(report_file):
target = report_file
break
if not target and response['items'] and response['nextPageToken']:
request = service.reports().files().list_next(request, response)
else:
break
Rita
page_token = nil
target = nil
loop do
result = service.list_report_files(profile_id, report_id,
page_token: page_token)
result.items.each do |file|
if target_file?(file)
target = file
break
end
end
page_token = (result.next_page_token if target.nil? && result.items.any?)
break if page_token.to_s.empty?
end
Ten en cuenta que el campo status
del recurso de archivo debe configurarse como REPORT_AVAILABLE
para que se pueda descargar.
Descarga directa
Para realizar una descarga directa, debes realizar una solicitud HTTP GET
autorizada al servicio de Archivos y, además, incluir el parámetro de consulta alt=media
. Una solicitud de ejemplo puede verse de la siguiente manera:
GET https://www.googleapis.com/dfareporting/v3.4/reports/12345/files/12345?alt=media HTTP/1.1 Authorization: Bearer your_auth_token
Ten en cuenta que la respuesta que recibas contendrá un redireccionamiento, por lo que lo ideal es que tu aplicación esté configurada para manejar esto automáticamente. Si prefieres realizar esta acción de forma manual, puedes encontrar la URL de redireccionamiento en el encabezado Location
de la respuesta.
La mayoría de las bibliotecas cliente oficiales de Google proporcionan métodos útiles para iniciar una descarga directa, como se muestra en el siguiente ejemplo. Si prefieres iniciar una descarga de forma manual, se proporciona una URL preconstruida en el campo apiUrl
del recurso del archivo.
C#
// Retrieve the file metadata.
File file = service.Files.Get(reportId, fileId).Execute();
if ("REPORT_AVAILABLE".Equals(file.Status)) {
// Create a get request.
FilesResource.GetRequest getRequest = service.Files.Get(reportId, fileId);
// Optional: adjust the chunk size used when downloading the file.
// getRequest.MediaDownloader.ChunkSize = MediaDownloader.MaximumChunkSize;
// Execute the get request and download the file.
using (System.IO.FileStream outFile = new System.IO.FileStream(GenerateFileName(file),
System.IO.FileMode.Create, System.IO.FileAccess.Write)) {
getRequest.Download(outFile);
Console.WriteLine("File {0} downloaded to {1}", file.Id, outFile.Name);
}
}
Java
// Retrieve the file metadata.
File file = reporting.files().get(reportId, fileId).execute();
if ("REPORT_AVAILABLE".equals(file.getStatus())) {
// Prepare a local file to download the report contents to.
java.io.File outFile = new java.io.File(Files.createTempDir(), generateFileName(file));
// Create a get request.
Get getRequest = reporting.files().get(reportId, fileId);
// Optional: adjust the chunk size used when downloading the file.
// getRequest.getMediaHttpDownloader().setChunkSize(MediaHttpDownloader.MAXIMUM_CHUNK_SIZE);
// Execute the get request and download the file.
try (OutputStream stream = new FileOutputStream(outFile)) {
getRequest.executeMediaAndDownloadTo(stream);
}
System.out.printf("File %d downloaded to %s%n", file.getId(), outFile.getAbsolutePath());
}
PHP
// Retrieve the file metadata.
$file = $this->service->files->get($reportId, $fileId);
if ($file->getStatus() === 'REPORT_AVAILABLE') {
try {
// Prepare a local file to download the report contents to.
$fileName = join(
DIRECTORY_SEPARATOR,
[sys_get_temp_dir(), $this->generateFileName($file)]
);
$fileResource = fopen($fileName, 'w+');
$fileStream = \GuzzleHttp\Psr7\stream_for($fileResource);
// Execute the get request and download the file.
$httpClient = $this->service->getClient()->authorize();
$result = $httpClient->request(
'GET',
$file->getUrls()->getApiUrl(),
[\GuzzleHttp\RequestOptions::SINK => $fileStream]
);
printf('<h3>Report file saved to: %s</h3>', $fileName);
} finally {
$fileStream->close();
fclose($fileResource);
}
}
Python
# Retrieve the file metadata.
report_file = service.files().get(
reportId=report_id, fileId=file_id).execute()
if report_file['status'] == 'REPORT_AVAILABLE':
# Prepare a local file to download the report contents to.
out_file = io.FileIO(generate_file_name(report_file), mode='wb')
# Create a get request.
request = service.files().get_media(reportId=report_id, fileId=file_id)
# Create a media downloader instance.
# Optional: adjust the chunk size used when downloading the file.
downloader = http.MediaIoBaseDownload(
out_file, request, chunksize=CHUNK_SIZE)
# Execute the get request and download the file.
download_finished = False
while download_finished is False:
_, download_finished = downloader.next_chunk()
print('File %s downloaded to %s' % (report_file['id'],
os.path.realpath(out_file.name)))
Rita
# Retrieve the file metadata.
report_file = service.get_file(report_id, file_id)
return unless report_file.status == 'REPORT_AVAILABLE'
# Prepare a local file to download the report contents to.
File.open(generate_file_name(report_file), 'w') do |out_file|
# Execute the download request. Providing a download destination
# retrieves the file contents rather than the file metadata.
service.get_file(report_id, file_id, download_dest: out_file)
puts format('File %s downloaded to %s', file_id,
File.absolute_path(out_file.path))
end
Descargas reanudables
Si descarga archivos de informes grandes, es posible que la descarga falle a mitad de camino. Para facilitar la recuperación y reanudar una descarga con errores, el servicio de archivos admite la funcionalidad de descarga parcial.
La descarga parcial implica solicitar partes específicas de un archivo, lo que te permite dividir las descargas grandes en fragmentos más pequeños. Para especificar qué parte de un archivo quieres descargar, incluye un rango de bytes en el encabezado HTTP Range
de la solicitud. Por ejemplo:
Range: bytes=500-999
Muchas bibliotecas cliente proporcionan la función de descarga parcial a través de un servicio de descarga multimedia. Consulta la documentación de la biblioteca cliente para obtener más detalles.
Descarga archivos en un navegador
Si quieres proporcionarles a los usuarios una forma de descargar un archivo directamente desde su navegador web, puedes usar la URL proporcionada en el campo browserUrl
del recurso Archivo. Puedes redireccionar a un usuario a esta URL u ofrecerla como un vínculo en el que se puede hacer clic. En cualquier caso, el usuario deberá acceder a una Cuenta de Google con acceso a los informes de Campaign Manager 360 y tener los permisos correctos para acceder al archivo especificado y, así, comenzar la descarga.
C#
File file = service.Files.Get(reportId, fileId).Execute();
String browserUrl = file.Urls.BrowserUrl;
Java
File file = reporting.files().get(reportId, fileId).execute();
String browserUrl = file.getUrls().getBrowserUrl();
PHP
$file = $this->service->files->get($reportId, $fileId);
$browserUrl = $file->getUrls()->getBrowserUrl();
Python
report_file = service.files().get(
reportId=report_id, fileId=file_id).execute()
browser_url = report_file['urls']['browserUrl']
Ruby
report_file = service.get_file(report_id, file_id)
browser_url = report_file.urls.browser_url