How to post video properties with youtube-data-api on c# - 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());
}

Related

308 permanent redirect with uploading PDF to REST API

I want to upload PDF to CrossEngage platform using HttpWebRequest or RestClient. As response I'm getting : 308 permanent redirect, but when i try this on POSTMAN all is fine (200 OK). What i'm not doing that POSTMAN is doing ?
//RestClient
byte[] dataBytes = System.IO.File.ReadAllBytes(path);
string converted = Convert.ToBase64String(dataBytes);
var client = new RestClient(Url+Action);
client.FollowRedirects = true;
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("x-xng-authtoken", AuthToken);
request.AddHeader("x-xng-apiversion", "2");
request.AddHeader("content-type", "application/pdf");
request.AddParameter("application/pdf", converted, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
return response.Content;
//HttpWebRequest
try
{
byte[] dataBytes = System.IO.File.ReadAllBytes(path);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + Action);
//request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.Headers.Add("X-XNG-ApiVersion", "2");
request.Headers.Add("X-XNG-AuthToken", AuthToken);
request.Method = method;
request.AllowAutoRedirect = true;
request.MaximumAutomaticRedirections = 1;
request.UseDefaultCredentials = false;
request.PreAuthenticate = true;
request.ContentLength = 0;
request.CookieContainer = new CookieContainer();
if (1 == 1)
{
request.ContentLength = dataBytes.Length;
request.ContentType = contentType;
using (Stream requestBody = request.GetRequestStream())
{
requestBody.Write(dataBytes, 0, dataBytes.Length);
}
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
catch (WebException webex)
{
string m = "";
using (HttpWebResponse response = (HttpWebResponse)webex.Response)
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
throw new Exception(reader.ReadToEnd());
}
}
I expect 200 OK status code
Thanks in advance
UPDATE: I have found a solution so it might help someone.
Simply you need to call location given in Location response header.
Hereby complete code :
try
{
byte[] dataBytes = System.IO.File.ReadAllBytes(path);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + Action);
//request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.Headers.Add("X-XNG-ApiVersion", "2");
request.Headers.Add("X-XNG-AuthToken", AuthToken);
request.Method = method;
request.AllowAutoRedirect = false;
if (1 == 1)
{
request.ContentLength = dataBytes.Length;
request.ContentType = contentType;
using (Stream requestBody = request.GetRequestStream())
{
requestBody.Write(dataBytes, 0, dataBytes.Length);
}
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if ((int)response.StatusCode >= 300 && (int)response.StatusCode <= 399)
{
var uriString = response.Headers["Location"];
var apiClient = (HttpWebRequest)WebRequest.Create(uriString);
apiClient.ContentType = contentType;
apiClient.Method = method;
apiClient.AllowAutoRedirect = false;
apiClient.Accept = "*/*";
apiClient.Headers.Add("X-XNG-ApiVersion", "2");
apiClient.Headers.Add("X-XNG-AuthToken", AuthToken);
apiClient.ContentLength = dataBytes.Length;
using (Stream requestBody = apiClient.GetRequestStream())
{
requestBody.Write(dataBytes, 0, dataBytes.Length);
}
var r = apiClient.GetResponse();
}
response.Close();
}
return "";
}
catch (WebException webex)
{
string m = "";
using (HttpWebResponse response = (HttpWebResponse)webex.Response)
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
throw new Exception(reader.ReadToEnd());
}
}

C# Post-Request Status 400 Bad Request

I am currently working on a C# Programm that is supposed to get Data from a REST API that I host.
The API requires a token for authentication which is returned from a POST request.
When I try to do the POST with C# I get a bad request (Status 400) but the GET request works fine. Now, My question is what I did wrong or what might be the cause for that error. When doing the request with postman both work perfectly.
The POST function:
void POST(string url, string jsonContent) {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(jsonContent);
request.ContentLength = byteArray.Length;
request.ContentType = #"application/json";
using (Stream dataStream = request.GetRequestStream()) {
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try {
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
length = response.ContentLength;
Console.WriteLine(response);
}
} catch (WebException ex) {
Console.WriteLine(ex);
}
}
The GET function:
string GET(string url) {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try {
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream()) {
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
return reader.ReadToEnd();
}
} catch (WebException ex) {
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream()) {
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}

How can I retrieve campaign's placements from AdWords through api(.net)

How can I retrieve campaign's placements from AdWords through api(.net)?
I'd seen this piece of code, but I can't do something similar via c#.
Also I try to get links through report PLACEMENT_PERFORMANCE_REPORT, but I can't.
public static string GetReport(AdWordsUser user, string customerId)
{
string postData = string.Format("__rdxml={0}", System.Web.HttpUtility.UrlEncode(#"<reportDefinition xmlns=""https://adwords.google.com/api/adwords/cm/v201506"">
<selector>
<fields>CampaignId</fields>
<fields>Impressions</fields>
<fields>Clicks</fields>
<fields>Cost</fields>
<fields>FinalUrls</fields>
<predicates>
<field>Impressions</field>
<operator>GREATER_THAN</operator>
<values>0</values>
</predicates>
</selector>
<reportName>Custom Campaign Performance Report</reportName>
<reportType>PLACEMENT_PERFORMANCE_REPORT</reportType>
<dateRangeType>ALL_TIME</dateRangeType>
<downloadFormat>XML</downloadFormat>
</reportDefinition>"));
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://adwords.google.com/api/adwords/reportdownload/v201506");
request.Headers.Add("Authorization", "Bearer " + user.OAuthProvider.AccessToken);
request.Headers.Add("developerToken", "MyToken");
request.Headers.Add("clientCustomerId", customerId);
request.Headers.Add("skipReportSummary", "true");
request.Headers.Add("skipReportHeader", "true");
request.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
var requestWriter = request.GetRequestStream();
requestWriter.Write(byteArray, 0, byteArray.Length);
requestWriter.Close();
string responseData = "";
try
{
StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());
responseData = responseReader.ReadToEnd();
responseReader.Close();
request.GetResponse().Close();
}
catch (Exception ex)
{
Console.WriteLine(ex);
return "";
}
return responseData;
}

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.

Images will not upload on web server but ok on local

I have some images on server i want to upload it on another server i make code to upload all images on server but it is OK to upload on local but i didn't know what is wrong in that it can't be upload on server
try
{
byte[] content;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
using (BinaryReader br = new BinaryReader(stream))
{
content = br.ReadBytes(500000);
br.Close();
}
response.Close();
string CompleteDPath = "ftp path";
string UName = "abc";
string PWD = "123";
WebRequest reqObj = WebRequest.Create(CompleteDPath + file_name);
reqObj.Method = WebRequestMethods.Ftp.UploadFile;
reqObj.Credentials = new NetworkCredential(UName, PWD);
reqObj.GetRequestStream().Write(content, 0, content.Length);
reqObj = null;
//FileStream fs = new FileStream(file_name, FileMode.Create);
//BinaryWriter bw = new BinaryWriter(fs);
//bw.Write(content);
//fs.Close();
//bw.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
have a try;
byte[] content;
HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create(url);
WebResponse response1 = request1.GetResponse();
Stream stream = response1.GetResponseStream();
using (BinaryReader br = new BinaryReader(stream))
{
content = br.ReadBytes((int)stream.Length);
br.Close();
}
response1.Close();
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp_path");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("abc", "123");
request.ContentLength = content.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(content, 0, content.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();

Categories