1

我在 Glassware 应用中订阅了时间线通知。当用户与 Glassware 比赛分享图像时,我收到了通知。现在我需要将该图像下载到我的 Glassware 应用程序中进行处理。

 Notification notification =
        new NewtonsoftJsonSerializer().Deserialize<Notification>(Request.InputStream);
    String userId = notification.UserToken;
    MirrorService service = new MirrorService(new BaseClientService.Initializer()
    {
        Authenticator = Utils.GetAuthenticatorFromState(Utils.GetStoredCredentials(userId))
    });

    if (notification.Collection == "timeline")
        {
        foreach (UserAction action in notification.UserActions)
        {
        if (action.Type == "SHARE")
            {
            TimelineItem item = service.Timeline.Get(notification.ItemId).Fetch();

             //i have to download content here.

            break;
            }
        else
            {
            Console.WriteLine(
                "I don't know what to do with this notification: " + action.ToString());
            }
        }
        }
4

1 回答 1

4

参考指南中描述了下载附件:

using System;
using Google.Apis.Mirror.v1;
using Google.Apis.Mirror.v1.Data;
using System.Net;
using System.IO;

public class MyClass {
  // ...

  /// <summary>
  /// Print an attachment's metadata.
  /// </summary>
  /// <param name="service">Authorized Mirror service.</param>
  /// <param name="itemId">ID of the timeline item the attachment belongs to.</param>
  /// <param name="attachmentId">ID of the attachment to print metadata for.</param>
  public static void PrintAttachmentMetadata(
      MirrorService service, String itemId, String attachmentId) {
    try {
      Attachment attachment = service.Timeline.Attachments.Get(itemId, attachmentId).Fetch();

      Console.WriteLine("Attachment content type: " + attachment.ContentType);
      Console.WriteLine("Attachment content URL: " + attachment.ContentUrl);
    } catch (Exception e) {
      Console.WriteLine("An error occurred: " + e.Message);
    }
  }

  /// <summary>
  /// Download a timeline items's attachment.
  /// </summary>
  /// <param name="service">Authorized Mirror service.</param>
  /// <param name="attachment">Attachment to download content for.</param>
  /// <returns>Attachment's content if successful, null otherwise.</returns>
  public static System.IO.Stream DownloadAttachment(
      MirrorService service, Attachment attachment) {
    try {
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
        new Uri(attachment.ContentUrl));
      service.Authenticator.ApplyAuthenticationToRequest(request);
      HttpWebResponse response = (HttpWebResponse)request.GetResponse();
      if (response.StatusCode == HttpStatusCode.OK) {
        return response.GetResponseStream();
      } else {
        Console.WriteLine(
          "An error occurred: " + response.StatusDescription);
        return null;
      }
    } catch (Exception e) {
      Console.WriteLine("An error occurred: " + e.Message);
      return null;
    }
  }

  // ...
}
于 2013-10-09T15:28:45.387 回答