I am having trouble calling Yahoo Gemini API to access Yahoo Gemini Advertising from my C# console (desktop) application.
Here are steps I used:
- Create an installed application on
https://developer.yahoo.com/apps/create/
. This gave me both{Client ID}
and{Client Secret}
. https://api.login.yahoo.com/oauth2/request_auth?client_id={Client ID} &redirect_uri=oob&response_type=code&language=en-us
. This will take me to the yahoo login screen where I sign in. Press the Agree button and the next screen shows the seven-letter authorization code (say nzbcns9). I write down this authorization code.Then I use the following code to try to get the access token:
class Program { static void Main(string[] args) { string clientId = {Client ID}; string secret = {Client Secret}; var request = WebRequest.Create(@"https://api.login.yahoo.com/oauth2/get_token"); request.Method = "POST"; SetBasicAuthHeader(request, clientId, secret); string postData = "grant_type=authorization_code&redirect_uri=oob&code=nzbcns9"; ASCIIEncoding encoding = new ASCIIEncoding(); byte[] byte1 = encoding.GetBytes(postData); request.ContentLength = byte1.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byte1, 0, byte1.Length); dataStream.Close(); request.ContentType = "application/x-www-form-urlencoded"; var response = request.GetResponse(); Console.WriteLine(((HttpWebResponse)response).StatusDescription); } static void SetBasicAuthHeader(WebRequest request, String userName, String userPassword) { string authInfo = userName + ":" + userPassword; authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); request.Headers["Authorization"] = "Basic " + authInfo; } }
Then I get
Unhandled Exception: System.Net.WebException: The remote server returned an error: (401) Unauthorized. at System.Net.HttpWebRequest.GetResponse().
What did I do wrong?
I also try to post the same message using Fiddler, I get
{"error":"invalid_request"}
I tried your code and what worked for me was to put the line
request.ContentType = "application/x-www-form-urlencoded";
BEFOREStream dataStream = request.GetRequestStream();
So this worked: