سؤال

I am attempting to connect to the Twitter API with these instructions

https://dev.twitter.com/docs/auth/application-only-auth

Here is my code:

var baseUrl = "http://api.twitter.com/";
var client = new RestClient(baseUrl);                     
var request = new RestRequest("/oauth2/token", Method.POST);

var concat = ConfigurationManager.AppSettings["TwitterConsumerKey"] + ":" +
     ConfigurationManager.AppSettings["TwitterConsumerSecret"];

string encodeTo64 = concat.EncodeTo64();

request.AddHeader("Authorization", "Basic " + encodeTo64);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
request.AddBody("grant_type=client_credentials");
IRestResponse restResponse = client.Execute(request);

EncodeTo64

static public string EncodeTo64(this string toEncode)
    {
        byte[] toEncodeAsBytes
              = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
        string returnValue
              = System.Convert.ToBase64String(toEncodeAsBytes);
        return returnValue;
    }

Response.Content is the following

"{\"errors\":[{\"code\":170,\"label\":\"forbidden_missing_parameter\",\"message\":\"Missing required parameter: grant_type\"}]}"

Is this part wrong?

request.AddBody("grant_type=client_credentials");

I have verified that my credentials are correct (I got that error before, but resolved it, so it should be OK).

هل كانت مفيدة؟

المحلول

The instructions on the Twitter page confused me. "The body of the request must be grant_type=client_credentials."

As for Restsharp, it's not AddBody, but AddParameter.

So:

request.AddParameter("grant_type", "client_credentials");
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top