附件受 OAuth 2.0 保护的方式与时间线项等其他实体相同。要访问它们,您必须提供有效的 OAuth 访问令牌。
默认情况下,对该 URL 的请求会返回附件元数据。如果您想要字节,则必须media
通过添加 GET 参数来指定响应格式alt=media
。官方客户端库为此提供了包装器。
参考文档和快速入门项目中有多种语言的示例。以下是我从这些来源复制的一些值得注意的内容:
原始 HTTP:
GET /mirror/v1/timeline/{timeline item id}/attachments/{attachment id}?alt=media HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer {auth token}
爪哇:
/**
* Download a timeline items's attachment.
*
* @param service Authorized Mirror service.
* @param itemId ID of the timeline item to download the attachment for.
* @param attachment Attachment to download content for.
* @return The attachment content on success, {@code null} otherwise.
*/
public static InputStream downloadAttachment(Mirror service, String itemId,
Attachment attachment) {
try {
HttpResponse resp =
service.getRequestFactory()
.buildGetRequest(new GenericUrl(attachment.getContentUrl()))
.execute();
return resp.getContent();
} catch (IOException e) {
// An error occurred.
e.printStackTrace();
return null;
}
}
PHP:
/**
* Download an attachment's content.
*
* @param string $timelineId ID of the timeline item the attachment belongs to.
* @param Google_Attachment $attachment Attachment's metadata.
* @return string The attachment's content if successful, null otherwise.
*/
function downloadAttachment($itemId, $attachment) {
$request = new Google_HttpRequest(
$attachment->getContentUrl(), 'GET', null, null);
$httpRequest = Google_Client::$io->authenticatedRequest($request);
if ($httpRequest->getResponseHttpCode() == 200) {
return $httpRequest->getResponseBody();
} else {
// An error occurred.
return null;
}
}
Python:
def download_attachment(service, attachment):
"""Download an attachment's content
Args:
service: Authorized Mirror service.
attachment: Attachment's metadata.
Returns:
Attachment's content if successful, None otherwise.
"""
resp, content = service._http.request(attachment['contentUrl'])
if resp.status == 200:
return content
else:
print 'An error occurred: %s' % resp
return None