c# - trying to retrieve languages json, timeline and more for my api results in bad authentication 401/403
i send consumer key and consumer key secret get bearer. i send bearer (even tried to encode it bas 64) but got unauthorized or bad request:( (401/403) - i’m using oauth2
attaching my code (would appriciate any help i can get)
try
{
var postBody = "grant_type=client_credentials";
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(string.Format("https://api.twitter.com/oauth2/token"));
authRequest.Headers.Add("Authorization", GetAuthHeader(fetchParams));
authRequest.Method = "POST";
authRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
authRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (Stream stream = authRequest.GetRequestStream())
{
byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);
stream.Write(content, 0, content.Length);
}
authRequest.Headers.Add("Accept-Encoding", "gzip");
WebResponse authResponse = authRequest.GetResponse();
// deserialize into an object
TwitAuthenticateResponse twitAuthResponse;
using (authResponse)
{
using (HttpWebResponse response = authRequest.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception(String.Format("Server error (HTTP {0}: {1}).",
response.StatusCode,
response.StatusDescription));
String responseString;
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
responseString = reader.ReadToEnd();
twitAuthResponse = JsonConvert.DeserializeObject<TwitAuthenticateResponse>(responseString);
}
}
}
// Do the timeline
HttpWebRequest timeLineRequest = (HttpWebRequest)WebRequest.Create(string.Format("https://api.twitter.com/1.1/help/languages.json"));
var timelineHeaderFormat = "{0} {1}";
timeLineRequest.Headers.Add("Authorization",
string.Format(timelineHeaderFormat,
twitAuthResponse.token_type,
Convert.ToBase64String(Encoding.UTF8.GetBytes(twitAuthResponse.access_token))));
timeLineRequest.Headers.Add("Accept-Encoding", "gzip");
timeLineRequest.Host = "api.twitter.com";
timeLineRequest.ContentType = "application/json; charset=utf-8";
timeLineRequest.Method = "GET";
WebResponse timeLineResponse = timeLineRequest.GetResponse();
var timeLineJson = string.Empty;
using (timeLineResponse)
{
using (var reader = new StreamReader(timeLineResponse.GetResponseStream()))
{
timeLineJson = reader.ReadToEnd();
}
}
}
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
LocalLogger.WriteToEventLog(reader.ReadToEnd());
}
}
catch (Exception e)
{
HandleServiceException(e);
}