Download file from google drive on server - c#

I use an javascript picker to get file from my google drive, it's work well and i get then download url and acces_token from my drive
I would like to download bytes array from this file from my server, then i path the url and acces_token to it (with ajax), no problem
on server i would get data with this code (it's worked !!!)
public void DownloadFile(string url, string AccessToken)
{
try
{
byte[] BB;
using (WebClient wc = new WebClient())
{
wc.Headers.Add("Authorization", "Bearer " + AccessToken);
BB = wc.DownloadData(url);
}
}
catch (Exception ex)
{
throw ex;
}
}
now i get an 403 error ??
url are like "https://content.googleapis.com/drive/v2/files.....?key=mykey....."
what's changed on google server ?
thanks

If you want to download a file using the Drive API and setting the access token in the header, you have to do it by calling this url:
https://www.googleapis.com/drive/v2/files/[file-Id]?alt=media
As it's told in the Response section in the Files: get endpoint. It's really important the url parameter alt=media in order to make it work. Don't use an API Key.

Related

Dynamics 365 Online : REST Api call that has a '%2F' as variable in url

OK, so this has kept me busy for too long. Testing the api call with the SOAPUI or Restlett in Chrome I can get the expected result - a binary that represents a pdf or possibly html. I've highlighted the part of the Url in question in yellow (this does represent a document number that should be downloaded and in the parent system is "130318/HJRWIQ" but we cannot use the '/' in the url thus the 130318%2FHJRWIQ representation of the same in the web-api call.
Chrome Restlett Api test results:
Now, trying to do the same in c# this url returns a '
404 not found
and I suspect that the %2F is somehow encoded back to a '/' again.
Below is two different methods I tried (both doing the same) :
c# methods to download the same response;
internal static string DownloadData(string resourceUrl, string authorizationApi, StringBuilder sb)
{
using (var wc = new WebClient())
{
// copy data to byte[]
wc.Headers.Add("Content-Type", "application/pdf");
wc.Headers.Add("Authorization", authorizationApi);
wc.Headers.Add("OData-MaxVersion", "4.0");
wc.Headers.Add("OData-Version", "4.0");
var data = wc.DownloadData(new Uri(#resourceUrl));
sb.AppendLine(" url used\t" + wc.BaseAddress);
sb.AppendLine(" querystring value\t" + wc.Encoding);
return Convert.ToBase64String(data);
}
}
internal static string DownloadData(string resourceUrl, string authorizationApi, ITracingService trace)
{
try
{
using (var wc = new WebClient())
{
wc.Headers.Add("ContentType", " text/plain");
wc.Headers.Add("Authorization", authorizationApi);
//wc.Headers.Add("Content-Disposition", "attachment; filename='82400200813_-doc.pdf'");
//wc.Headers.Add("Transfer-Encoding", "chunked");
return wc.DownloadString(new Uri(#resourceUrl));
}
}
catch (Exception e)
{
trace.Trace("DOWNLOAD DATA EXCEPTION: \n" + e.Message + "\n" + e.InnerException);
}
return "";
}
The Exception logged as per above :
DOWNLOAD DATA EXCEPTION:
The remote server returned an error: (404) Not Found.
just ignore the string builder and tracing (this is used to debug remotely) as this runs online.
Anyone else ran into this before ? How do I get the url passed correctly ?
EDIT
Even MS reproduced this and does not have a workaround answer - I moved this code to an azure service that could do the get independently and pass the result back;

Exception during a WebClient request for a FTP download

I'm trying to develop a function that downloads a file in a FTP directory. I try this way
static void descargarFic(string ficFTP, string user, string pass, string dirLocal)
{
Library.WriteErrorLog(ficFTP + " -> " + dirLocal);
try
{
WebClient client = new WebClient();
client.Credentials = new NetworkCredential(user, pass);
client.DownloadFile(ficFTP, dirLocal);
Library.WriteErrorLog("Done");
client.Dispose();
}
catch(Exception e)
{
Library.WriteErrorLog(e.Message);
}
}
The WriteErrorLog write on a file the string passed. So, I'm calling that function in this way:
descargarFic("ftp://something-here/incoming/file.xml.gz", "anonymous", "password", #"C:\folder1\file.xml.gz");
But I receive the exception Exception during a WebClient request for a FTP download when I try to download it.
I'm pretty sure that it's some kind of problem with the URI, but I didn't realize where it is.
EDIT: Using Library.WriteErrorLog(e.InnerException);
The exception given is
The given access path's format is not supported.

Unable to create a shared link using the Box API V2

UPDATE: I figured it out and posted the answer below.
All I'm trying to do is update any file attribute. Description, name, anything, but no matter how I format it I get a 403.
I need to be able to modify a file so it can be shared via the Box API from a cloud app. I'm updating someone else's code from V1, but they are no longer available... I've tried many things but mostly just get 403 Forbidden errors.
There are no issues with OAuth2, that works fine and I can list files and folders, but can not modify them. This question is about sharing, but I can't change a description either. The box account is mine and I authenticate with my admin credentials. Any suggestions would be appreciated.
Here is the method I am using. I pass in the fileId and token and I've left out try/catch etc. for brevity.
string uri = string.Format("https://api.box.com/2.0/files/{0}", fileId);
string body = "{\"shared_link\": {\"access\": \"open\"}}";
byte[] postArray = Encoding.ASCII.GetBytes(body);
using (var client = new WebClient())
{
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.Headers.Add("Authorization: Bearer " + token);
var response = client.UploadData(uri, postArray);
var responseString = Encoding.Default.GetString(response);
}
Thanks.
Okay, My Homer Simpson moment...
UploadData is a POST, I needed to do a PUT. Here is the solution.
string uri = String.Format(UriFiles, fileId);
string response = string.Empty;
string body = "{\"shared_link\": {\"access\": \"open\"}}";
byte[] postArray = Encoding.ASCII.GetBytes(body);
try
{
using (var client = new WebClient())
{
client.Headers.Add("Authorization: Bearer " + token);
client.Headers.Add("Content-Type", "application/json");
response = client.UploadString(uri, "PUT", body);
}
}
catch (Exception ex)
{
return null;
}
return response;
try changing your content type to 'multipart/form-data'?
I just looked up the api at: https://developers.box.com/docs/#files-upload-a-file
and it looks like the server is expecting a multipart post
here is stack overflow post on posting multipart data:
ASP.NET WebApi: how to perform a multipart post with file upload using WebApi HttpClient

writing files to a remote http server

I have created a virtual directory with read and write access to everyone on Machine B. I am running web application 1 on Machine A. Now the requirement is to upload a file to remote http location from this web application. Machine A web application i is configured with anonymous authentication.
i am not able to implement the above requirement successfully. Please suggest whether this approach is correct or not?
public override bool UploadFile()
{
byte[] postData;
try
{
postData = this.FileData;
using (WebClient client = new WebClient())
{
client.Credentials = CredentialCache.DefaultCredentials;
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.UploadData(this.UrlString, "PUT", postData);
}
return true;
}
catch (Exception ex)
{
throw new Exception("Failed to upload", ex.InnerException);
}
}
i have tried the example given in the below location
http://code.msdn.microsoft.com/CSASPNETRemoteUploadAndDown-a80b7cb5
unfortunately i could not able to make it work. I am using IIS7 on both machine A & B
Please suggest.

Wikipedia query returns error 403

I'm querying Wikipedia using the following code, but I always get an error (403 forbidden). When I type the exact same url in my browser, however, it works. I've been using the same code before to query other web apis, so I am not sure what's causing the trouble.
private static string query(string text)
{
text = text.Replace(" ", "%20");
string url = "http://en.wikipedia.org/w/api.php?action=opensearch&search=" + text + "&format=json&callback=spellcheck";
WebClient client = new WebClient();
client.Headers.Add("User-Agent", "whatever"); // <-- this line was missing
try
{
string response = client.DownloadString(url);
return response;
}
catch(Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
Try setting the user agent header to something that matches your browser. If this doesn't work, fire up Fiddler, take a peek at your browser headers and copy them to your web request.
http://msdn.microsoft.com/en-us/library/system.net.webclient.headers.aspx
EDIT
The advice I gave was generic. Please observe the policies of the website you are downloading from, as spoofing a browser user-agent may contravene policy or be considered malicious by default:
http://meta.wikimedia.org/wiki/User-Agent_policy :
Do not copy a browser's user agent for your bot, as bot-like behavior with a browser's user agent will be assumed malicious.

Categories