Uploading files to Google Drive with non-ASCII letters in the titles - c#

How can I upload a file to Google Drive if it contains non-ASCII symbols in
its title?
Currently I'm using this method to start the upload to Google Drive. But if I'm passing a filename which contains non-ASCII letters, it is fails returning ParseError in the JSON response.
public string startUploadSession(string mimeType, long fileLength, string filename)
{
string uri = "https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable" + "&access_token=" + account.accessInfo.access_token;
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("X-Upload-Content-Type", mimeType);
request.Headers.Add("X-Upload-Content-Length", fileLength.ToString());
// Here we're providing file metadata
File file = new File();
file.title = filename;
string requestBody = toJsonString(file);
request.ContentLength = requestBody.Length;
System.IO.Stream requestStream = request.GetRequestStream();
requestStream.Write(requestBody.ToByteArray(), 0, requestBody.Length);
requestStream.Close();
try
{
var response = request.GetResponse();
var reader = new System.IO.StreamReader(response.GetResponseStream());
var responseBody = reader.ReadToEnd();
return response.Headers["Location"];
}
catch (WebException ex)
{
System.IO.StreamReader reader = new System.IO.StreamReader(ex.Response.GetResponseStream());
string error = reader.ReadToEnd();
Logger.Error(error, "Getting upload uri");
return null;
}
}
OK. This is my bug. Fixed part of code:
System.IO.Stream requestStream = request.GetRequestStream();
byte[] utf8Bytes = requestBody.ToByteArray();
requestStream.Write(utf8Bytes, 0, utf8Bytes.Count());
requestStream.Close();

Related

HTTP post XML data in C# (Error in request.GetRequestStream())

I need to Post the XML data to a URL.But I am facing some Error in the (Stream requestStream = request.GetRequestStream()) Line
Errror Image .
I have saved the xml in the file and provided the path for that . I think there is Issue while passing XML Data but when I try to use the same XML in the POSTMan using POSTmethod.I can able to get the response Data.
This is the reference link HTTP post XML data in C#
And here is my code
static void Main(string[] args)
{
string url = "*****************";
XmlDocument Xdoc = new XmlDocument();
Xdoc.Load(#"Path of the xml file");
var sw = new StringWriter();
Xdoc.Save(sw);
string result = sw.ToString();
string response = **********.postXMLData(url, result);
Console.WriteLine(response);
Console.ReadLine();
}
public static string postXMLData(string destinationUrl, String requestXml)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
request.ContentType = "text/xml; encoding=utf-8";
request.ContentLength = bytes.Length;
request.Method = "POST";
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream).ReadToEnd();
return responseStr;
}
return null;
}

Calling web service with XML post method and getting response in XML format which is very slow response

Here I am getting proper result but my problem is very slow response getting from the server.
Please suggest any other fastest method to call web service. Help appreciated.
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><availabilityRequest cancelpolicy = \"Y\">with more condition</availabilityRequest>
String responseStr = postXMLData("http://service-url", xml);
XmlDocument doc = new XmlDocument();
doc.LoadXml(responseStr);
public String postXMLData(string destinationUrl, string requestXml)
{
string responseStr = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
responseStr = new StreamReader(responseStream).ReadToEnd().Trim();
}
return responseStr;
}

How to post video properties with youtube-data-api on c#

I try to upload videos to my youtube account with youtube api v3 on asp.net. I searched a lot but didn't find any code sample to do this. Actually now i can upload videos somehow but i can't give name, description etc. to my videos. Here's my code which i use to upload my videos.
Uri uri = new Uri("https://www.googleapis.com/upload/youtube/v3/videos?part=snippet");
WebClient wc = new WebClient();
wc.Headers.Add("Authorization", "Bearer {access_token}");
byte[] file = File.ReadAllBytes(Server.MapPath("/videos/test.mp4"));
byte[] response = wc.UploadData(uri, file);
string jSonResult = String.Format("\nResult received was {0}",
Encoding.ASCII.GetString(response));
return jSonResult;
Don't know if you already found a solution.
But this code works on my machine! ;)
byte[] jsonBytes = Encoding.UTF8.GetBytes(json);
//byte[] file = File.ReadAllBytes(videoFilePath);
using (var fileStream = new FileStream(videoFilePath, FileMode.Open))
{
Uri uri = new Uri("https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet,status");
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = "POST";
request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + authToken);
request.ContentLength = jsonBytes.Length;
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("X-Upload-Content-Length", fileStream.Length.ToString());
request.Headers.Add("X-Upload-Content-Type", "video/*");
string location = string.Empty;
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(jsonBytes, 0, jsonBytes.Length);
}
try
{
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
location = response.Headers["Location"];
}
}
catch (WebException ex)
{
Response.Write(ex.ToString());
}
request = (HttpWebRequest) WebRequest.Create(location);
request.Method = "PUT";
request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + authToken);
request.ContentLength = fileStream.Length;
request.ContentType = "video/*";
using (Stream dataStream = request.GetRequestStream())
{
byte[] buffer = new byte[fileStream.Length];
var data = fileStream.Read(buffer, 0, buffer.Length);
dataStream.Write(buffer, 0, data);
//dataStream.Write(file, 0, file.Length);
}
try
{
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
}
}
catch (WebException ex)
{
Response.Write(ex.ToString());
}

Uploading image to imgur causes: The Uri string is too long

im trying to develope C# application that uses Imgur api to upload images.
this is my upload function:
public static string PostToImgur(string imagFilePath, string apiKey)
{
byte[] imageData;
FileStream fileStream = File.OpenRead(imagFilePath);
imageData = new byte[fileStream.Length];
fileStream.Read(imageData, 0, imageData.Length);
fileStream.Close();
string uploadRequestString = "image=" + Uri.EscapeDataString(System.Convert.ToBase64String(imageData)) + "&key=" + apiKey;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://api.imgur.com/3/image");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Headers["Authorization"] = "Client-ID abd937cc5e11dc9";
StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream());
streamWriter.Write(uploadRequestString);
streamWriter.Close();
WebResponse response = webRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
return responseReader.ReadToEnd();
}
if im uploading small pictures (20kb) all works fine.
but when im uploding bigger images (500kb) i get the error:
Invalid URI: The Uri string is too long.
what can i do?
i succeed to upload large images by dividing the base64 string
this is the working code:
public static string PostToImgur(string imagFilePath, string apiKey)
{
byte[] imageData;
FileStream fileStream = File.OpenRead(imagFilePath);
imageData = new byte[fileStream.Length];
fileStream.Read(imageData, 0, imageData.Length);
fileStream.Close();
const int MAX_URI_LENGTH = 32766;
string base64img = System.Convert.ToBase64String(imageData);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < base64img.Length; i += MAX_URI_LENGTH)
{
sb.Append(Uri.EscapeDataString(base64img.Substring(i, Math.Min(MAX_URI_LENGTH, base64img.Length - i))));
}
string uploadRequestString = "key=" + apiKey + "&title=" + "imageTitle" +
"&caption=" + "img" + "&image=" + sb.ToString();
// string uploadRequestString = "image=" + Uri.EscapeDataString(System.Convert.ToBase64String(imageData)) + "&key=" + apiKey;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://api.imgur.com/3/image");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Headers["Authorization"] = "Client-ID abd937cc5e11dc9";
StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream());
streamWriter.Write(uploadRequestString);
streamWriter.Close();
WebResponse response = webRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
return responseReader.ReadToEnd();
}
thanks to all.
They way it works is the image is converted like so: System.Convert.ToBase64String(imageData)
That is added to the URI and sent to the server to be decoded back to an image.
You will not be able to get around this issue with a single URI, as its inherent in imgur's design.
Read this for the maximum length a URI can be: What is the maximum length of a URL in different browsers?

How to get response from Base CRM API authentication

I am trying to get a response from Base API, but i keep getting "500 Internal Server Error" error. I want to get at least 401 HTTP Response which means that authentication call has failed. Here is a description of using Base API authentication:
http://dev.futuresimple.com/api/authentication
And here is my code:
public string Authenticate()
{
string result = "";
string url = "https://sales.futuresimple.com/api/v1/";
string email = "mail#mail.com";
string password = "pass";
string postData = "email=" + email + "&password=" + password;
HttpWebRequest request = null;
Uri uri = new Uri(url + "authentication.xml");
request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/xml";
request.ContentLength = postData.Length;
using (Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(postData);
writeStream.Write(bytes, 0, bytes.Length);
writeStream.Close();
}
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
}
catch (WebException ex)
{
ex = ex;
}
return result;
}
You're setting the ContentType to application/xml - this is the type of the request body. The body you're sending (string postData = "email=" + email + "&password=" + password;) is form-encoded instead of xml. Just skipping the line request.ContentType = "application/xml"; should do the trick. Alternatively you can encode your request body as xml.

Categories