twitter application oauth 403 - c#

I am attempting to do application oauth as outlined here: https://dev.twitter.com/docs/api/1.1/post/oauth2/token
but my attempts to do so result in 403(forbidden) The C# code I am attempting is:
String key = ConfigurationManager.AppSettings["TwitterConsumerKey"];
String secret = ConfigurationManager.AppSettings["TwitterConsumerSecret"];
String bearerCredentials = HttpUtility.UrlEncode(key) + ":" + HttpUtility.UrlEncode(secret);
bearerCredentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(bearerCredentials));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.twitter.com/oauth2/token");
request.Method = "POST";
request.Headers.Add("Authorization", "Basic " + bearerCredentials);
request.ContentType = "Content-Type: application/x-www-form-urlencoded;charset=UTF-8";
string postData = "grant_type=client_credentials";
byte[] data = System.Text.Encoding.UTF8.GetBytes(postData);
request.ContentLength = data.Length;
request.GetRequestStream().Write(data, 0, data.Length);
WebResponse response = request.GetResponse();
Any suggestions on what I am doing wrong here?

Leaving this question up in case someone else makes the same silly mistake I did, writing it up pointed out to me the answer this line
request.ContentType = "Content-Type: application/x-www-form-urlencoded;charset=UTF-8";
string postData = "grant_type=client_credentials";
had an unecessary Content-Type being set it should be
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
string postData = "grant_type=client_credentials";

Related

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";

Postmates API not working

I am using postmates Delivery Quote API for the last one year, And it is working good by the time when I checked.
But now it seems to be not working
It is throwing an exception with an HTML text with some enable cookies and captcha
I can't understand if i am missing some updates from postmates
Here is my coding
HttpWebRequest req = WebRequest.Create(new Uri("https://api.postmates.com/v1/customers/" + PostmatesCustomerId + "/delivery_quotes")) as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.Headers.Add("Authorization", "Basic " + Base64string);
StringBuilder paramz = new StringBuilder();
paramz.Append("pickup_address=" + PickUpAddress + "&dropoff_address=" + DeliveryAddress);
byte[] formData =
UTF8Encoding.UTF8.GetBytes(paramz.ToString());
req.ContentLength = formData.Length;
// Send the request:
using (Stream post = req.GetRequestStream())
{
post.Write(formData, 0, formData.Length);
}
string responseString = null;
using (HttpWebResponse resp = req.GetResponse()
as HttpWebResponse)
{
StreamReader reader =
new StreamReader(resp.GetResponseStream());
responseString = reader.ReadToEnd();
}
If you're outside of the US, try using a VPN as a workaround to test.

Error 400 with YouTube API and 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.

Content-Length or Chunked Encoding cannot be set for an operation that does not write data

I get this Error :
Content-Length or Chunked Encoding cannot be set for an operation that does not write data
How can I resolve it?
Here is my code:
string xmlreq="<?xml version='1.0' encoding='iso-8859-1'?><methodCall><methodName>GetBalanceAndDate</methodName><params><param><value><struct><member><name>originNodeType</name><value><string>EXT</string></value></member><member><name>originHostName</name><value><string>FashionMasala</string></value></member><member><name>transactionType</name><value><string>FashionMasala</string></value></member><member><name>transactionCode</name><value><string>FashionMasala</string></value></member><member><name>externalData1</name><value><string>FashionMasala_VAS</string></value></member><member><name>externalData2</name><value><string>FashionMasala_VAS</string></value></member><member><name>originTransactionID</name><value><string>1</string></value></member><member><name>originTimeStamp</name><value><dateTime.iso8601>"+DateTime.UtcNow.ToString("o")+"</dateTime.iso8601></value></member><member><name>subscriberNumberNAI</name><value><int>1</int></value></member><member><name>subscriberNumber</name<value><string>923030025659</string></value></member></struct></value></param></params></methodCall>";
HttpWebRequest webrequest =(HttpWebRequest)WebRequest.Create(url);
webrequest.ContentType = "text/xml";
webrequest.Method = "GET";
webrequest.ContentLength =xmlreq.Length;
webrequest.Headers.Add("Authorization", "Basic " + oatuh);
HttpWebResponse webresponse =(HttpWebResponse)webrequest.GetResponse();
You're not actually writing (or encoding) your data. Try something like this:
string xmlreq = ...
var data = Encoding.ASCII.GetBytes( xmlreq );
var webrequest = (HttpWebRequest)WebRequest.Create( url );
webrequest.ContentType = "text/xml";
webrequest.Method = "GET";
webrequest.ContentLength = data.Length;
webrequest.Headers.Add( "Authorization", "Basic " + oatuh );
using( var stream = webrequest.GetRequestStream() )
stream.Write( data, 0, data.Length );
var webresponse = (HttpWebResponse)webrequest.GetResponse();
I went with ASCII because why not, you'll have to decide on the proper encoding obviously.
Edit: And also, as CodesInChaos points out, it doesn't make much sense to send data in a GET request. Are you sure you're not supposed to use POST?

cURL with user authentication in C#

I want to do the following cURL request in c#:
curl -u admin:geoserver -v -XPOST -H 'Content-type: text/xml' \
-d '<workspace><name>acme</name></workspace>' \
http://localhost:8080/geoserver/rest/workspaces
I have tried using a WebRequest:
string url = "http://localhost:8080/geoserver/rest/workspaces";
WebRequest request = WebRequest.Create(url);
request.ContentType = "Content-type: text/xml";
request.Method = "POST";
request.Credentials = new NetworkCredential("admin", "geoserver");
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("<workspace><name>my_workspace</name></workspace>");
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();
WebResponse response = request.GetResponse();
...
But I get an error: (400) Bad request.
If I change the request credentials and add the authentication in the header:
string url = "http://localhost:8080/geoserver/rest/workspaces";
WebRequest request = WebRequest.Create(url);
request.ContentType = "Content-type: text/xml";
request.Method = "POST";
string authInfo = "admin:geoserver";
request.Headers["Authorization"] = "Basic " + authInfo;
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("<workspace><name>my_workspace</name></workspace>");
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();
WebResponse response = request.GetResponse();
...
Then I get: (401) Unauthorised.
My question is: Should I use another C# class like WebClient or HttpWebRequest or do I have to use the curl bindings for .NET?
All comments or guidance would be appreciated.
HTTP Basic authentication requies everything after "Basic " to be Base64-encoded, so try
request.Headers["Authorization"] = "Basic " +
Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo));
The solution to my question was changing the ContentType property. If I change the ContentType to
request.ContentType = "text/xml";
the request works in both cases, if I also convert the authInfo to a Base64String in the last example like Anton Gogolev suggested.
Using:
request.ContentType = "application/xml";
request.Credentials = new NetworkCredential(GEOSERVER_USER, GEOSERVER_PASSWD);
also works. The second sets authentication information.
Or, if you want to use HttpClient:
var authValue = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("admin:geoserver")));
try
{
var client = new HttpClient()
{
DefaultRequestHeaders = { Authorization = authValue }
};
string url = "http://{BASE_URL}";
client.BaseAddress = new Uri(url);
var content = new StringContent("<workspace><name>TestTestTest</name></workspace>",
Encoding.UTF8, "text/xml");
var response = await client.PostAsync($"/{PATH_TO_API}/", content);
response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync();
}
catch (HttpRequestException ex)
{
Console.WriteLine(ex.Message);
}

Categories