Reputation: 89
Im trying to download files from google disk. Auth Class:
internal static class Perm_AppData
{
private static string[] scopes = { DriveService.Scope.DriveFile };
private static DriveService service = Autorization();
internal static DriveService Service { get { return service; } }
private static DriveService Autorization()
{
UserCredential credential;
using (var stream = GetCliSecStream())
{
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
scopes,
"user",
CancellationToken.None,
new FileDataStore(auth, true)).Result;
}
return new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = applicationName
});
}
private static Stream GetCliSecStream()
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(uSec);
writer.Flush();
stream.Position = 0;
return stream;
}
}
After that, I chose an account and confirmed the rights of the application. Next is the request to download the file
internal static MemoryStream DownloadFile(string fileId = null, string fileName = null)
{
using (new Watcher($"Download {fileName} {fileId}"))
{
GetRequest request = null;
if (fileId != null)
{
request = service.Files.Get(fileId);
}
else
{
if (fileName != null)
{
request = service.Files.Get(ViewDrive(SearchParameter.name, new string[] { fileName }).First().Id);
}
else
{
throw new Exception("You need at least one not null parameter to download");
}
}
request.Fields = "id, name";
var fileMemoryStream = new MemoryStream();
request.Download(fileMemoryStream);
return fileMemoryStream;
}
}
Downloading the file throws an exception (System.Net.WebException: The remote server returned an error: (407) Requires proxy authentication):
Error: System.TypeInitializationException: Инициализатор типа "Updater.UnDloadAP I" выдал исключение. ---> System.TypeInitializationException: Инициализатор типа "Updater.Perm_AppData" выдал исключение. ---> System.AggregateException: Произо шла одна или несколько ошибок. ---> System.Net.Http.HttpRequestException: Произо шла ошибка при отправке запроса. ---> System.Net.WebException: Удаленный сервер возвратил ошибку: (407) Требуется аутентификация посредника. в System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, Tra nsportContext& context) в System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
--- Конец трассировки внутреннего стека исключений --- в Google.Apis.Http.ConfigurableMessageHandler.d__55.MoveNext() --- Конец трассировка стека из предыдущего расположения, где возникло исключение --- в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNoti fication(Task task) в Google.Apis.Auth.OAuth2.Requests.TokenRequestExtenstions.d__0 .MoveNext() --- Конец трассировка стека из предыдущего расположения, где возникло исключение --- в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNoti fication(Task task) в Google.Apis.Auth.OAuth2.Flows.AuthorizationCodeFlow.d__35. MoveNext() --- Конец трассировка стека из предыдущего расположения, где возникло исключение --- в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNoti fication(Task task) в Google.Apis.Auth.OAuth2.Flows.AuthorizationCodeFlow.d__30.MoveNext() --- Конец трассировка стека из предыдущего расположения, где возникло исключение --- в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNoti fication(Task task) в Google.Apis.Auth.OAuth2.AuthorizationCodeInstalledApp.d__8. MoveNext() --- Конец трассировка стека из предыдущего расположения, где возникло исключение --- в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNoti fication(Task task) в Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.d__4.M oveNext() --- Конец трассировка стека из предыдущего расположения, где возникло исключение --- в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNoti fication(Task task) в Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.d__1.M oveNext() --- Конец трассировки внутреннего стека исключений ---
в System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledE xceptions) в System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotificat ion) в System.Threading.Tasks.Task
1.get_Result() в Updater.Perm_AppData.Autorization() в C:\Users\User\Documents\Visual Studio Projects\SMNote\Updater\Classes\API\Perm_AppData.cs:строка 27
I need something like:
WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;
I do not get an error if I connect to the Internet without a proxy
Post updated #1:
The following code normally passes through the proxy
var request = (HttpWebRequest)WebRequest.Create(link);
request.Credentials = CredentialCache.DefaultCredentials;
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
Therefore, I believe that you need to somehow manually add a proxy to the request for google drive
Post updated #2:
The following code normally passes through the proxy
internal static void DoIt()
{
try
{
var t = DownloadPageAsync();
Console.WriteLine("Downloading page...");
Console.WriteLine(t.Result);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private static async Task<string> DownloadPageAsync()
{
var proxy = WebRequest.DefaultWebProxy;
proxy.Credentials = CredentialCache.DefaultCredentials;
var httpClientHandler = new HttpClientHandler()
{
Proxy = proxy
};
using (HttpClient client = new HttpClient(httpClientHandler))
{
using (HttpResponseMessage response = await client.GetAsync("https://mail.ru"))
{
using (HttpContent content = response.Content)
{
string result = await content.ReadAsStringAsync();
return result.Substring(0, 50);
}
}
}
}
Upvotes: 1
Views: 1187
Reputation: 89
Google Drive code works fine. Problem is that i have limited access to Proxy. Thanks toJon Skeet that helped to find the problem
Upvotes: 1