如何将Google云端硬盘凭据传递给WebRequest?

时间:2017-08-22 04:32:14

标签: c# google-drive-api httpwebrequest webrequest

我是C#的初学者。

我想在窗口格式here中将缩略图加载到PictureBox。

我的方法是使用webrequest打开上面的路径并从响应中获取图像。

但是,由于我不知道如何通过google驱动器凭据将凭据设置为webrequest,因此无效。

如果有人可以提供帮助,那就太棒了。提前谢谢。

1 个答案:

答案 0 :(得分:0)

为了帮助您入门,您可能需要开始使用sample code中的documentation

using Google.Apis.Authentication;
using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;

using System.Net;
// ...

public class MyClass {

  // ...

  /// <summary>
  /// Print a file's metadata.
  /// </summary>
  /// <param name="service">Drive API service instance.</param>
  /// <param name="fileId">ID of the file to print metadata for.</param>
  public static void printFile(DriveService service, String fileId) {
    try {
      File file = service.Files.Get(fileId).Execute();

      Console.WriteLine("Title: " + file.Title);
      Console.WriteLine("Description: " + file.Description);
      Console.WriteLine("MIME type: " + file.MimeType);
    } catch (Exception e) {
      Console.WriteLine("An error occurred: " + e.Message);
    }
  }

  /// <summary>
  /// Download a file and return a string with its content.
  /// </summary>
  /// <param name="authenticator">
  /// Authenticator responsible for creating authorized web requests.
  /// </param>
  /// <param name="file">Drive File instance.</param>
  /// <returns>File's content if successful, null otherwise.</returns>
  public static System.IO.Stream DownloadFile(
      IAuthenticator authenticator, File file) {
    if (!String.IsNullOrEmpty(file.DownloadUrl)) {
      try {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
            new Uri(file.DownloadUrl));
        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;
      }
    } else {
      // The file doesn't have any content stored on Drive.
      return null;
    }
  }

  //...

}

文档中描述了parameters(参数名称,变量类型和描述)。

您可以在代码中阅读this guide以了解身份验证和授权的实施情况。

OAuth 2.0

  

本文档介绍了OAuth 2.0,何时使用它,如何获取   客户端ID,以及如何将其与Google API客户端库配合使用   .NET。

在阅读文档时,您会看到给定的sample code,它们将作为您实施的参考。

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

using Google.Apis.Auth.OAuth2;
using Google.Apis.Books.v1;
using Google.Apis.Books.v1.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;

namespace Books.ListMyLibrary
{
    /// <summary>
    /// Sample which demonstrates how to use the Books API.
    /// https://developers.google.com/books/docs/v1/getting_started
    /// <summary>
    internal class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            Console.WriteLine("Books API Sample: List MyLibrary");
            Console.WriteLine("================================");
            try
            {
                new Program().Run().Wait();
            }
            catch (AggregateException ex)
            {
                foreach (var e in ex.InnerExceptions)
                {
                    Console.WriteLine("ERROR: " + e.Message);
                }
            }
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }

        private async Task Run()
        {
            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { BooksService.Scope.Books },
                    "user", CancellationToken.None, new FileDataStore("Books.ListMyLibrary"));
            }

            // Create the service.
            var service = new BooksService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Books API Sample",
                });

            var bookshelves = await service.Mylibrary.Bookshelves.List().ExecuteAsync();
            ...
        }
    }
}