Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 针对Xamrin.Android的Google Drive ApI V3迁移_C#_Xamarin.android - Fatal编程技术网

C# 针对Xamrin.Android的Google Drive ApI V3迁移

C# 针对Xamrin.Android的Google Drive ApI V3迁移,c#,xamarin.android,C#,Xamarin.android,请告诉我如何迁移到Google Drive API v2或V3。我找到了与java相关的迁移的所有答案。我找不到与Google Drive API v2或V3等效的xamarin nuget包 我尝试过这个Xamarin.GooglePlayServices.Drivenuget包,但是在这个包中,所有的驱动api都被去除了 有人能在xamarin中尝试google drive集成吗?请帮助我。这是我的尝试 GoogleSignInOptions gso = new GoogleSign

请告诉我如何迁移到Google Drive API v2或V3。我找到了与java相关的迁移的所有答案。我找不到与Google Drive API v2或V3等效的xamarin nuget包

我尝试过这个Xamarin.GooglePlayServices.Drivenuget包,但是在这个包中,所有的驱动api都被去除了

有人能在xamarin中尝试google drive集成吗?请帮助我。这是我的尝试

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DefaultSignIn)
                .RequestEmail()
                .Build();

    var mGoogleApiClient = new GoogleApiClient.Builder(this)
                .EnableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .AddApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .Build();


     MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
            .SetTitle(_backupFolderName)
            .Build();
        IDriveFolderDriveFolderResult result;
        try
        {
            result = await DriveClass.DriveApi.GetRootFolder(_googleApiClient)
                .CreateFolderAsync(_googleApiClient, changeSet);
        }
        catch (Exception)
        {
            return null;
        }

我找不到任何支持Xamarin和OAuth身份验证的google drive nuget包。因此,我找到了使用Http客户端RESTAPI的方法

请按照以下步骤操作

  • 使用Google开发者控制台创建OAuth客户端id
  • 将客户端Id与重定向等其他信息一起使用

    public class GoogleAuthenticator : OAuth2Authenticator
    {
    public static OAuth2Authenticator Auth;
    
    public GoogleAuthenticator(string clientId, string scope, Uri authorizeUrl, Uri redirectUrl,
        GetUsernameAsyncFunc getUsernameAsync = null, bool isUsingNativeUi = false) : base(clientId, scope,
        authorizeUrl, redirectUrl, getUsernameAsync, isUsingNativeUi)
    {
        Auth = new OAuth2Authenticator(clientId, string.Empty, scope,
            authorizeUrl,
            redirectUrl,
            new Uri(GoogleDriveConfig.AccessTokenUri),
            null, true);
    
        Auth.Completed += OnAuthenticationCompleted;
        Auth.Error += OnAuthenticationFailed;
    }
    
    public void OnAuthenticationCompleted(object sender,AuthenticatorCompletedEventArgs e)
    {
        if (e.IsAuthenticated)
        {
            AuthenticationCompleted?.Invoke(e.Account.Properties["access_token"],
                e.Account.Properties["refresh_token"], e.Account.Properties["expires_in"]);
        }
    
    }
    
    public void OnAuthenticationFailed(object sender, AuthenticatorErrorEventArgs e)
    {
    
    }
    
  • 启动浏览器

    public void SignInToDrive(Activity context)
      {
        Intent loginUi = Auth.GetUI(context);
    
        CustomTabsConfiguration.IsShowTitleUsed = false;
        CustomTabsConfiguration.IsActionButtonUsed = false;
        context.StartActivity(loginUi);
      }
    
  • 创建GoogleAuthorInterceptor活动

      [Activity(Label = "GoogleAuthInterceptor")] 
      [  IntentFilter ( actions: new[] 
      {Intent.ActionView}, 
       Categories = new[] { Intent.CategoryDefault, 
      Intent.CategoryBrowsable }, 
      DataSchemes = new[] {"YOUR PACKAGE NAME"}, DataPaths = new[] { "/oauth2redirect" 
       } ) ]
    
      public class GoogleAuthInterceptor : Activity
     {
       protected override void OnCreate(Bundle savedInstanceState)
      {
        base.OnCreate(savedInstanceState);
        Uri uriAndroid = Intent.Data;
    
        System.Uri uri = new System.Uri(uriAndroid.ToString());
    
            var intent = new Intent(ApplicationContext, typeof(MainActivity));
            intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop);
            StartActivity(intent);
    
        GoogleAuthenticator.Auth.OnPageLoading(uri);
    
        Finish();
        return;
    }
    }
    
  • 上传文件到谷歌硬盘

    private async Task<bool> UpdateFile(string accessToken,string fileId,long fileSize,Stream stream)
    {
       HttpRequestMessage sessionRequest = new HttpRequestMessage(new HttpMethod("PATCH"), "upload/drive/v3/files/" + $"{fileId}");
        sessionRequest.Headers.Add("Authorization", "Bearer " + accessToken);
        sessionRequest.Headers.Add("X-Upload-Content-Type", "*/*");
        sessionRequest.Headers.Add("X-Upload-Content-Length", fileSize.ToString());
        sessionRequest.Content = new StreamContent(stream);
        sessionRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("*/*");
    
        using (var response = await _httpClient.SendAsync(sessionRequest))
        {
            return response.IsSuccessStatusCode;
        }
    }
    
    此基本地址适用于以下所有google drive API

    HttpClient\u HttpClient=HttpClient??新的HttpClient
    {
    BaseAddress=新Uri(),
    };
    专用异步任务CreateResumableSession(字符串accessToken、字符串文件名、长文件大小、字符串folderId)
    {
    var sessionRequest=new
    HttpRequestMessage(HttpMethod.Post,“upload/drive/v3/files?uploadType=resubable”);
    sessionRequest.Headers.Add(“授权”、“承载人”+accessToken);
    sessionRequest.Headers.Add(“X-Upload-Content-Type”,“*/*”);
    sessionRequest.Headers.Add(“X-Upload-Content-Length”,fileSize.ToString());
    字符串正文=“{\'name\”:\”+fileName+“\”,\“parents\”:[\”“+folderId+“\”]}”;
    sessionRequest.Content=新的StringContent(body);
    sessionRequest.Content.Headers.ContentType=新的MediaTypeHeaderValue(“应用程序/json”);
    使用(var sessionResponse=await_httpClient.SendAsync(sessionRequest))
    {
    返回会话响应;
    };
    
  • 更新谷歌硬盘中的文件

    private async Task<bool> UpdateFile(string accessToken,string fileId,long fileSize,Stream stream)
    {
       HttpRequestMessage sessionRequest = new HttpRequestMessage(new HttpMethod("PATCH"), "upload/drive/v3/files/" + $"{fileId}");
        sessionRequest.Headers.Add("Authorization", "Bearer " + accessToken);
        sessionRequest.Headers.Add("X-Upload-Content-Type", "*/*");
        sessionRequest.Headers.Add("X-Upload-Content-Length", fileSize.ToString());
        sessionRequest.Content = new StreamContent(stream);
        sessionRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("*/*");
    
        using (var response = await _httpClient.SendAsync(sessionRequest))
        {
            return response.IsSuccessStatusCode;
        }
    }
    
    private async Task UpdateFile(字符串accessToken、字符串fileId、长文件大小、流)
    {
    HttpRequestMessage sessionRequest=新的HttpRequestMessage(新的HttpMethod(“补丁”),“upload/drive/v3/files/”+$“{fileId}”);
    sessionRequest.Headers.Add(“授权”、“承载人”+accessToken);
    sessionRequest.Headers.Add(“X-Upload-Content-Type”,“*/*”);
    sessionRequest.Headers.Add(“X-Upload-Content-Length”,fileSize.ToString());
    sessionRequest.Content=新的流内容(流);
    sessionRequest.Content.Headers.ContentType=新的MediaTypeHeaderValue(“*/*”);
    使用(var response=await_httpClient.sendsync(sessionRequest))
    {
    返回response.IsSuccessStatusCode;
    }
    }
    
  • 下载文件

      public async Task<Stream> DownloadFile(string accessToken, string fileId)
    {
        var request = new HttpRequestMessage(HttpMethod.Get,"drive/v3/files"+ $"/{fileId}" + "?fields=*&alt=media");
        request.Headers.Add("Authorization", "Bearer " + accessToken);
    
        var response = await _httpClient.SendAsync(request);
    
        if (response.IsSuccessStatusCode)
        {
            var contents = await response.Content.ReadAsStreamAsync();
            return contents;
        }
    
        return null; 
    }
    
    public异步任务下载文件(string accessToken,string fileId)
    {
    var request=newhttprequestmessage(HttpMethod.Get,“drive/v3/files”+$“/{fileId}”+“?fields=*&alt=media”);
    添加(“授权”、“承载人”+accessToken);
    var response=await\u httpClient.sendsync(请求);
    if(响应。IsSuccessStatusCode)
    {
    var contents=await response.Content.ReadAsStreamAsync();
    返回内容;
    }
    返回null;
    }
    
  • 获取所有文件

    public  async Task<GoogleDriveItem> GetFiles(string folderId, string accessToken)
    {  
        var request = new HttpRequestMessage(HttpMethod.Get,
            "drive/v3/files" +"?q=parents%20%3D%20'" +
            $"{folderId}" +
            "'%20and%20trashed%20%3D%20false&fields=files(id%2Cname%2Ctrashed%2CmodifiedTime%2Cparents)");
        request.Headers.Add("Authorization", "Bearer " + accessToken);
        request.Headers.Add("Accept", "application/json");
        request.Headers.CacheControl = new CacheControlHeaderValue() { NoCache = true 
        };
    
        using (var response = await _httpClient.SendAsync(request))
        {
            var content = await response.Content.ReadAsStringAsync();
            return (JsonConvert.DeserializeObject<GoogleDriveItem>(content));
        }
    }
    
    公共异步任务GetFiles(字符串folderId、字符串accessToken)
    {  
    var请求=新的HttpRequestMessage(HttpMethod.Get,
    “驱动器/v3/文件”+“?q=parents%20%3D%20'”+
    $“{folderId}”+
    ““%20和%20垃圾%20%3D%20false&fields=文件(id%2Cname%2Ctrashed%2CmodifiedTime%2Cparents)”;
    添加(“授权”、“承载人”+accessToken);
    添加(“接受”、“应用程序/json”);
    request.Headers.CacheControl=new CacheControlHeaderValue(){NoCache=true
    };
    使用(var response=wait_httpClient.SendAsync(请求))
    {
    var content=await response.content.ReadAsStringAsync();
    返回(JsonConvert.DeserializeObject(content));
    }
    }
    

  • 你找到什么了吗?我现在也有同样的问题。是的。我努力了很多,终于找到了。如果你仍然没有找到。请评论。我将上传答案,这将非常有帮助,谢谢。我现在没有笔记本电脑。我将上传明天的答案,没有问题!谢谢你的回复,我有一个问题:
    OAuth2Authenticator在哪里来自?好的,找到了。是Xamarin.Auth。如果您不介意的话,如果我还有任何问题,我会告诉您的。再次感谢