Error 400 with YouTube API and C#? - c#

I am trying to update the title to a video, with an authorized put in C#:
string postUrl = "https://www.googleapis.com/youtube/v3/videos?part=snippet&access_token=" + this.access_token;
string postData = "id=" + this.videoID +
"&snippet[title]=" + Uri.EscapeDataString(status.Text) +
"&snippet[categoryId]=20";
byte[] postByte = Encoding.UTF8.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
request.Method = "PUT";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postByte.Length;
request.Timeout = 15000;
try
{
Stream putStream = request.GetRequestStream();
putStream.Write(postByte, 0, postByte.Length);
putStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
catch (WebException err)
{
MessageBox.Show(err.Message);
}
The above code shows the following error:
The remote server returned an error: (400) Bad Request.
What am I doing wrong?

I figured it out. This particular endpoint needs a json responce, instead of a x-www-form-urlencoded response.

Related

ALM Rest API : site-session returns 'The remote server returned an error: (400) Bad Request.'

I am getting '(400) Bad Request.' when I try complete authenticate against an ALM REST API, the first part (authentication) is successful) and I get the LWSSO_COOKIE_KEY, but site-session always fails with a 400 error code.
What am I doing wrong please... very confused!
// Authentication XML : 0 = User, 1 = Password
private const string AuthenticationXML = #"<alm-authentication>" +
"<user>{0}</user><password>{1}</password></alm-authentication>";
baseRequestURL = settings.QualityCentreURL + "/qcbin/";
Authentication is done first (and is successful) :
string authRequest = baseRequestURL + "authentication-point/alm-authenticate";
HttpWebRequest myauthrequest = (HttpWebRequest)WebRequest.Create(authRequest);
string xml = String.Format(AuthenticationXML, qcSettings.Username, qcSettings.Password);
byte[] Requestbytes = Encoding.UTF8.GetBytes(xml);
myauthrequest.Method = "POST";
myauthrequest.ContentType = "application/xml";
myauthrequest.ContentLength = Requestbytes.Length;
myauthrequest.Accept = "application/xml";
Stream RequestStr = myauthrequest.GetRequestStream();
RequestStr.Write(Requestbytes, 0, Requestbytes.Length);
RequestStr.Close();
HttpWebResponse myauthres = (HttpWebResponse)myauthrequest.GetResponse();
authenticationCookie = myauthres.Headers.Get("Set-Cookie");
The Site-Session code is :
public void GetSiteSession()
{
// Creat the web request fore site-session.
string request = baseRequestURL + "rest/site-session";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(request);
string xml = String.Empty;
byte[] requestbytes = Encoding.UTF8.GetBytes(xml);
// Update the attributes before sending.
webRequest.Method = "POST";
webRequest.ContentType = "application/xml";
webRequest.Accept = "application/xml";
webRequest.Headers.Set(HttpRequestHeader.Cookie, authenticationCookie);
try
{
Stream requestStream = webRequest.GetRequestStream();
requestStream.Write(requestbytes, 0, requestbytes.Length);
requestStream.Close();
HttpWebResponse webRequestResponse = (HttpWebResponse)webRequest.GetResponse();
Stream responseStream = webRequestResponse.GetResponseStream();
XDocument doc = XDocument.Load(responseStream);
}
catch (System.Net.WebException except)
{
Console.WriteLine(except.Message);
}
}
I have tried cutting ;Path=/;HTTPOnly from LWSSO_COOKIE_KEY as per this question, but to no avail.
The API reference I found(here) seems to be a big vague or, possibly that I haven't understood it... :P
Apologies, it seems that with 12.53 I should have been using 'api/authentication/sign-in'
string requestURL = baseRequestURL + "api/authentication/sign-in";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);
var credentials = String.Format("{0}:{1}", qcSettings.Username, qcSettings.Password);
request.CookieContainer = authenticationCookieContainer;
request.Headers.Set(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));
var authResponse = request.GetResponse();
errorString = String.Empty;
}
catch (System.Net.WebException except)
{
errorString = except.Message;
return false;
}
errorString = String.Empty;
return true;
}

Post with parameters using HttpWebRequest in C#

Having the following code:
var request = HttpWebRequest.Create("https://api.channeladvisor.com/oauth2/token");
request.ContentType = "text/html";
request.Method = "POST";
request.Headers.Add("cache-control","no-cache");
request.Headers.Add("Authorization", "Basic " + Base64Translator.ToBase64(System.Text.Encoding.ASCII, devKey+":"+sharedSecret));
string postData = " grant_type=refresh_token&refresh_token=a12SL1bHhJwerxM2NFth2efZw0yIW7462kAhR43UCJA";
var data = Encoding.ASCII.GetBytes(postData);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
What's wrong? I can't do the request but I can using external programs like Postman. Do you see anything wrong in the header?
Error: "The remote server returned an error: (400) Bad Request."
Thanks!
Your content type should be application/x-www-form-urlencoded.
request.ContentType = "application/x-www-form-urlencoded";

C# WebRequest - HTTP: 403 Forbidden ('_xsrf' argument missing from POST)

I'm stucked here at getting a WebResponse from HTTPWebRequest.
The WebRequest.GetResponse() Method throws a WebException
("500 Internal Server Error"). When i read the returned HTML it says:
HTTP 403: Forbidden ('_xsrf' argument missing from POST)
Anyone knows this Error or knows what Im doing wrong?
(Im trying to log in to a Website using POST)
EDIT:
My sourcecode:
private String GetLoginCookies(String pHTTPurl, String pUserIDwithFormID, String pPasswordWithFormID)
{
String loginPageUrl = pHTTPurl;
CookieContainer cookieContainer = new CookieContainer();
var Request = (HttpWebRequest)WebRequest.Create(loginPageUrl);
Request.CookieContainer = cookieContainer;
Request.Method = "GET";
WebResponse Response = Request.GetResponse();
HttpWebResponse HttpResponse = Response as HttpWebResponse;
CookieCollection cookies = null;
if (HttpResponse != null)
{
//Cookies die benötigt werden um den Loginvorgang abzuschließen
cookies = HttpResponse.Cookies;
}
string formParams = string.Format(pUserIDwithFormID + "&" + pPasswordWithFormID);
Request = (HttpWebRequest)WebRequest.Create(loginPageUrl);
Request.CookieContainer = cookieContainer;
Request.UserAgent = "I am not a Bot! Ok maybe..";
WebResponse resp = null;
Request.ContentType = "application/x-www-form-urlencoded";
Request.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
Request.ContentLength = bytes.Length;
using (Stream os = Request.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
try
{
resp = Request.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
String TestResponse = sr.ReadToEnd();
}
}
catch (WebException WE)
{
DebugConsole.AppendText("HTTP Error:" + WE.Message + Environment.NewLine);
String HTML = new StreamReader(WE.Response.GetResponseStream()).ReadToEnd();
DebugConsole.AppendText(HTML);
return null;
}
String cookieHeader = resp.Headers["Set-cookie"];
if (String.IsNullOrEmpty(cookieHeader))
return null;
else
return cookieHeader;
}
This is actually because the web method requires anti csrf (cross site request forgery, more info here: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)) validation parameter. What you can do, is to append the csrf value to the request header:
postHeaders.Add("X-CSRFToken", CSRF);
Maybe you can paste your source code here if you need any help with that, so we can look after it
OK! Solution found!
After getting the response of the Log-In site, search in the "Set-cookie" Header for _xsrf. This is the Token you have to put in the header of the next POST request.

remote server returned an error 500 internal server error

I have to call a method of web service which contains array as part of parameters.
I dont want to pass any value for the parameter of type Array.
I tried passing null,""(empty)but the web Method call returns 'remote server returned an error 500 internal server error 'as error.I am unable to figure out the cause?Need some help.
Here is my code
string post_data = "SessionID=" + sessionID + "&From=" + "" + "&To=" + "" + "&Changed=" + "" ;
// this is where we will send it
string uri = "test.asmx";
// create a request
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
// turn our request string into a byte stream
byte[] postBytes = Encoding.ASCII.GetBytes(post_data);
// this is important - make sure you specify type this way
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
// now send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
// grab te response and print it out to the console along with the status code
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(new StreamReader(response.GetResponseStream()).ReadToEnd());
Console.WriteLine(response.StatusCode);

Error getting response stream (ReadDone2): Receive Failure

Help me please.
After sending post query i have webexception "Error getting response stream (ReadDone2): Receive Failure". help get rid of this error. thanks.
piece of code
try
{
string queryContent = string.Format("login={0}&password={1}&mobileDeviceType={2}/",
login, sessionPassword, deviceType);
request = ConnectionHelper.GetHttpWebRequest(loginPageAddress, queryContent);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())//after this line //occurs exception - "Error getting response stream (ReadDone2): Receive Failure"
{
ConnectionHelper.ParseSessionsIdFromCookie(response);
string location = response.Headers["Location"];
if (!string.IsNullOrEmpty(location))
{
string responseUri = Utils.GetUriWithoutQuery(response.ResponseUri.ToString());
string locationUri = Utils.CombineUri(responseUri, location);
result = this.DownloadXml(locationUri);
}
response.Close();
}
}
catch (Exception e)
{
errorCout++;
errorText = e.Message;
}
//Methot GetHttpWebRequest
public static HttpWebRequest GetHttpWebRequest(string uri, string queryContent)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Proxy = new WebProxy(uri);
request.UserAgent = Consts.userAgent;
request.AutomaticDecompression = DecompressionMethods.GZip;
request.AllowWriteStreamBuffering = true;
request.AllowAutoRedirect = false;
string sessionsId = GetSessionsIdForCookie(uri);
if (!string.IsNullOrEmpty(sessionsId))
request.Headers.Add(Consts.headerCookieName, sessionsId);
if (queryContent != string.Empty)
{
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
byte[] SomeBytes = Encoding.UTF8.GetBytes(queryContent);
request.ContentLength = SomeBytes.Length;
using (Stream newStream = request.GetRequestStream())
{
newStream.Write(SomeBytes, 0, SomeBytes.Length);
}
}
else
{
request.Method = "GET";
}
return request;
}
using (Stream newStream = request.GetRequestStream())
{
newStream.Write(SomeBytes, 0, SomeBytes.Length);
//try to add
newStream.Close();
}
In my case the server did not send a response body. After fixing the server, the "Receive Failure" vanished.
So you have two options:
Don't request a response stream, if you can live without it.
Make sure the server sends a response body.
E.g., instead of
self.send_response(200)
self.wfile.close()
the Python server code should be
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write("Thanks!\n")
self.wfile.close()
its not Xamarin or .NET's bug. :wink:
your server side endpoint fails when requesting. :neutral:
check your API endpoint if you own the api or contact support if you are getting API from third party company or service.
why it happens randomly : :wink:
because bug is in your inner if or loop blocks and it happens when it goes through this buggy loop or if.
best regards. :smile:

Categories