i have tried using your code snippet above (along with a couple of functions to do hmac and build the signature base string) and i’m still getting a 400 bad response. would you mind taking a look at my code to see if you can find my mistake?

Hi,

I am struggling from past two days with “POST statuses/update” I am getting 401 - Unauthorized.
Please help me out.

I am pasting my code here

public Hashtable startTweetText(String access_token, String access_token_secret, String tweet) throws UnsupportedEncodingException {
	String oauth_token = access_token;
	String oauth_token_secret = access_token_secret;

	// generate authorization header
	String get_or_post = "POST";
	String oauth_signature_method = "HMAC-SHA1";

	String uuid_string = UUID.randomUUID().toString();
	uuid_string = uuid_string.replaceAll("-", "");
	String oauth_nonce = uuid_string; // any relatively random alphanumeric
										// string will work here

	// get the timestamp
	Calendar tempcal = Calendar.getInstance();
	long ts = tempcal.getTimeInMillis();// get current time in milliseconds
	String oauth_timestamp = (new Long(ts / 1000)).toString(); // then
																// divide by
																// 1000 to
																// get
																// seconds

	String text = URLEncoder.encode(tweet,"UTF-8");
	
	// the parameter string must be in alphabetical order, "text" parameter
	// added at end
	String parameter_string = "include_entities=true" + "&oauth_consumer_key=" + twitter_consumer_key
			+ "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method="
			+ oauth_signature_method + "&oauth_timestamp="
			+ oauth_timestamp + "&oauth_token=" + URLEncoder.encode(oauth_token, "UTF-8")
			+ "&oauth_version=1.0&status=" + text;
	System.out.println("parameter_string=" + parameter_string);

	String twitter_endpoint = "https://api.twitter.com/1.1/statuses/update.json";
	
	String signature_base_string = get_or_post + "&"
			+ URLEncoder.encode(twitter_endpoint,"UTF-8") + "&" + URLEncoder.encode(parameter_string,"UTF-8");
	System.out.println("signature_base_string=" + signature_base_string);
	String oauth_signature = "";
	try {
		oauth_signature = computeSignature(signature_base_string,
				twitter_consumer_secret + "&" + URLEncoder.encode(oauth_token_secret,"UTF-8"));
	} catch (GeneralSecurityException e) {
		e.printStackTrace();
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	}
	String authorization_header_string = "OAuth oauth_consumer_key=\""
			+ twitter_consumer_key
			+ "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\""
			+ oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce
			+ "\",oauth_version=\"1.0\",oauth_signature=\""
			+ URLEncoder.encode(oauth_signature,"UTF-8") + "\",oauth_token=\""
			+ URLEncoder.encode(oauth_token,"UTF-8") + "\"";
	System.out.println("authorization_header_string="
			+ authorization_header_string);
	
	HttpParams params = new BasicHttpParams(); 	
	params.setParameter("include_entities", "true");
	
	HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
	
	HttpClient httpclient = new DefaultHttpClient(params);
	Hashtable<String, String> table = null;
	try {
		
		HttpPost httppost = new HttpPost(twitter_endpoint);	
		
		
		
		
		 httppost.addHeader("Accept", "*/*");
         httppost.addHeader("Connection", "close");
         httppost.addHeader("User-Agent", "OAuth gem v0.4.4");
         httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        // httppost.addHeader("Content-Length", "76");
         httppost.addHeader("Authorization", authorization_header_string);
		
		//added
		List <NameValuePair> nvps = new ArrayList <NameValuePair>();
		//nvps.add(new BasicNameValuePair("include_entities", "true"));
         nvps.add(new BasicNameValuePair("status", tweet));
         //add complete
         
        httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        HttpResponse response = httpclient.execute(httppost);
		
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		String responseBody = httpclient.execute(httppost, responseHandler);
		table = callStringTokenizer(responseBody);
		/*oauth_token = responseBody.substring(
				responseBody.indexOf("oauth_token=") + 12,
				responseBody.indexOf("&oauth_token_secret="));*/
		System.out.println(responseBody);
		
	} catch (ClientProtocolException cpe) {
		System.out.println(cpe.getMessage());
	} catch (IOException ioe) {
		System.out.println(ioe.getMessage());
	} finally {
		
		httpclient.getConnectionManager().shutdown();
	}
	return table;
}

x-oauthflow-twitter://callback?oauth_token=Zqu0vh50r9gK8RIXFByi9v91altMpPPWwhS1mktHN8&oauth_verifier=0CSCeK56O0DXgxAJGFuIoA0F7YqCK3xhsacJsZS8A

im newto all this please help it wont work

We seem to be equally stymied with oAuth and API v1.1.

Our site used to pull tweets with Twitter Pull, but recently stopped doing so and wont show anything more current than late June. We had previously updated to twitter_pull-7.x-1.0-rc5, which worked for a while; we understand that we need a version that uses oAuth, and want to comply, but this has been nothing but trouble. Were doing this on a staging site, in hopes I can get it working and then replicate it on the live site.

I updated to the latest versions of Drupal’s modules for:

Twitter Pull
Twitter
oAuth

I successfully registered the app at dev.twitter.com/apps/new. I have copied (and re-copied, and corrected MANY times) the callback URL and secret keys, and generated the required tokens

But I every time I try to add an authenticated Twitter account to our site, it circles back to the following error message: “Could not obtain a valid token from the Twitter API. Please review the configuration.” But, where or how to get the correct token is a mystery.

I’ve followed all the steps at: Installing the Twitter module | Twitter | Drupal Wiki guide on Drupal.org, including ensuring the callback URL is correct, and making sure the OpenSSL extension is enabled in PHP by adding: “extension=openssl.so”.

But that didn’t fix the problem; the most current error message in the Drupal logs is as follows:

exception ‘TwitterException’ with message ‘Gone’ in /home/site/public_html/sites/all/modules/contrib/twitter/twitter.lib.php:151 Stack trace: #0 /home/site/public_html/sites/all/modules/contrib/twitter/twitter.lib.php(114): Twitter->request(‘https://api.twi…’) #1 /home/site/public_html/sites/all/modules/contrib/twitter/twitter.lib.php(51): Twitter->auth_request(‘https://api.twi…’, Array) #2 /home/site/public_html/sites/all/modules/contrib/twitter/twitter.pages.inc(339): Twitter->get_request_token() #3 /home/site/public_html/includes/form.inc(1464): twitter_auth_account_form_submit(Array, Array) #4 /home/site/public_html/includes/form.inc(860): form_execute_handlers(‘submit’, Array, Array) #5 /home/site/public_html/includes/form.inc(374): drupal_process_form(‘twitter_auth_ac…’, Array, Array) #6 /home/site/public_html/includes/form.inc(131): drupal_build_form(‘twitter_auth_ac…’, Array) #7 /home/site/public_html/sites/all/modules/contrib/twitter/twitter.pages.inc(133): drupal_get_form(‘twitter_auth_ac…’) #8 [internal function]: twitter_user_settings() #9 /home/site/public_html/includes/menu.inc(517): call_user_func_array(‘twitter_user_se…’, Array) #10 /home/site/public_html/index.php(21): menu_execute_active_handler() #11 {main}

That doesn’t make sense, because the same Twitter feeds continue to exist: we’re logging in and updating it, so that “resource” continues to exist- this “410” error shouldn’t apply?

Anyone run into this before?

cepten twitter keyfini yaşayın diye telefona mesaj geldi ama ben nasıl olacağını bilmiyorum .Nası olacağı hakkında yardımcı olusanız sevinirim . Selamlar.

Hi

I am a ColdFusion developer. I got an error while trying to call 1.1 API for twitter feeds.
Could you please help me to solve the error?

I am tried the following code. I am miss anything?





Thanks.

Why aren’t my consumer key, consumer secret, access token, and access token secret not working? It just says to check twitter but everything is connected correctly .

i am using blackberry webworks for my phonegap application.

in my application i need to login with twitter ,i am sending request to https://api.twitter.com/oauth/request_token, but as a response i am not getting auth_token & seceret… apart of that response.text=“” coming ,i m not able to understand what is the issue.

Twitterizer Library working fine at local system but not on server after deploy, every time return “unauthorize” status when call update() . Any Idea ?

Make sure all your calls are https. See https://dev.twitter.com/discussions/24239 for more details.

Hello, I am a newbie in programming. I try to send messages to twitter but I have this error:

04-07 12:42:34.430: E/Twitter Login Error(24153): > 401:Authentication credentials (Authentication overview | Docs | Twitter Developer Platform) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
04-07 12:42:34.430: E/Twitter Login Error(24153): <?xml version="1.0" encoding="UTF-8"?>
04-07 12:42:34.430: E/Twitter Login Error(24153):
04-07 12:42:34.430: E/Twitter Login Error(24153): Required oauth_verifier parameter not provided
04-07 12:42:34.430: E/Twitter Login Error(24153): /oauth/access_token
04-07 12:42:34.430: E/Twitter Login Error(24153):

I try to regenerate keys, change callback… but I dont know how to fix my error.
Anybody knows how to fix that error pls? Thanks

Twitter Auth, IOS app and adding a callback URL is my subject:

I Understand the OAuth flow, but our current IOS app does not use a callback URL, instead it plugs into X-Auth. To enable Twitter Login on a webpage if I add a callback url, will that break my IOS login flow?

If adding a callback url to my settings breaks my existing flow, how can I use the same twitter app to sign into my IOS app and website APP without using a PIN and breaking or changing the existing IOS flow. Since people have older version of the app I don’t want to prevent them from logging in and using our application if I make a twitter application change.

Thanks for any information

I’m trying to complete the first step of "Sign in with Twitter"by posting to https://api.twitter.com/1.1/oauth/request_token. I’m using the following information.
I’ve tested my signature string using an expression tester at http://quonos.nl/oauthTester/ and used their dummy data to test my code, both of which worked. I believe may be using HttpWebCLient incorrectly. I’ve included a all of my code (old keys) and relevant libraries used. Thanks in advance.

signature key =qbnhoaMIcJmXKx9O65vc13ABkzs=

Authorization: Oauth oauth_consumer_key=“fbpvyf2acxvtc8axbsbgGssDK”, oauth_nonce=“NjM1MzkzMTQ5MDExODQyMTE0”, oauth_signature=“qbnhoaMIcJmXKx9O65vc13ABkzs%3D”, oauth_signature_method=“HMAC-SHA1”, oauth_timestamp=“1403736101”, oauth_version=“1.0”

signature_string=POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_consumer_key%3Dfbpvyf2acxvtc8axbsbgGssDK%26oauth_nonce%3DNjM1MzkzMTQ5MDExODQyMTE0%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1403736101%26oauth_version%3D1.0

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Security.Cryptography; using System.IO; using System.Globalization;
namespace ConsoleApplication1
{
    class TwitterApp
    {

        private static string CONSUMER_KEY = "fbpvyf2acxvtc8axbsbgGssDK";
        private static string CONSUMER_SECRET = "2dSgDnGq1xn7fOSTo7gd9H6BzdqyymThkVM4VDFLTLPjAJueer";
        private static string STR_URL ="https://api.twitter.com/oauth/request_token";
        private static string OAUTH_SIGNATURE_METHOD = "HMAC-SHA1";
        private static string OAUTH_VERSION = "1.0";
        private static string OAUTH_TOKEN = "201555372-tJ7vR33pFeQTFPVNLYbKnYfOdngILaeEhmnXH3dK";
        private static string OAUTH_TOKEN_SECRET ="KHgKOie82SdK8w4Hmu6tcprTFrFggTYpfm68sAxZlOzY9";
        private static int TIME_STAMP=0;

        private static int request_count = 0;
        private static byte[] nonce_bytes = new byte[31];
        private static string unique_nonce_string = null;

        public string gCONSUMER_KEY { get { return CONSUMER_KEY; } }
        public string gCONSUMER_SECRET { get { return CONSUMER_SECRET; } }
        public string gOAUTH_SIGNATURE_METHOD { get { return OAUTH_SIGNATURE_METHOD; } }
        public string gOAUTH_VERSION { get { return OAUTH_VERSION; } }
        public string gOAUTH_TOKEN { get { return OAUTH_TOKEN; } }
        public string gOAUTH_TOKEN_SECRET { get { return OAUTH_TOKEN; } }
        public string gTIME_STAMP { get { return TIME_STAMP.ToString(); } }
        public string g_unique_nonce_string { get { return unique_nonce_string; } }  
 

        private static Random rand=new Random();

             
      public TwitterApp()
        {
           
        }

      public static void CreateNonce()
        {
            // create a new nonce key if null
            if (nonce_bytes == null)
            {
                rand.NextBytes(nonce_bytes);
                request_count = 0;
            }
          
        }

      public static string GetOauthSignature()
      {
         


          var parameter_string = Uri.EscapeDataString("oauth_consumer_key") + "=" + Uri.EscapeDataString(TwitterApp.CONSUMER_KEY) + "&" +
                                 Uri.EscapeDataString("oauth_nonce")+ "=" + Uri.EscapeDataString(TwitterApp.unique_nonce_string) + "&" +
                                 Uri.EscapeDataString("oauth_signature_method")+"=" + Uri.EscapeDataString(TwitterApp.OAUTH_SIGNATURE_METHOD )+ "&"+
                                 Uri.EscapeDataString("oauth_timestamp")+ "=" + Uri.EscapeDataString(TwitterApp.TIME_STAMP.ToString()) + "&"+
                                                            Uri.EscapeDataString("oauth_version") + "=" + Uri.EscapeDataString(TwitterApp.OAUTH_VERSION);

          var signature_base_string = "POST" + '&' + Uri.EscapeDataString(STR_URL) + '&' + Uri.EscapeDataString(parameter_string);
          var signing_key = Uri.EscapeDataString(TwitterApp.CONSUMER_SECRET) + "&";

          var hmac = new HMACSHA1(System.Text.Encoding.ASCII.GetBytes(signing_key));
          byte[] result = hmac.ComputeHash(System.Text.Encoding.ASCII.GetBytes(signature_base_string));

          return Convert.ToBase64String(result);


      }
      public static void DateTimeToUnixTimestamp()
      {
          TIME_STAMP= (int)(DateTime.Now - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds;
      }

      public static void GenerateUniqueNonce()
      {
         
          
          TwitterApp.unique_nonce_string = Convert.ToBase64String(new ASCIIEncoding().GetBytes( DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture)));

      }
    
              
    }

    class Authorize : TwitterApp
    {
       public Authorize() { }

        public string GetAuthorizationHeader(TwitterApp AuthorizeApp)
       {
           TwitterApp.CreateNonce();
            TwitterApp.GenerateUniqueNonce();
            TwitterApp.DateTimeToUnixTimestamp();

            string signature_string = TwitterApp.GetOauthSignature();

            var QUOTE = "\"";
            var QUOTE_COMMA = "\","+" ";
            string Authorization = Uri.EscapeDataString("oauth_consumer_key") + "=" + QUOTE + Uri.EscapeDataString(AuthorizeApp.gCONSUMER_KEY) + QUOTE_COMMA +
                    Uri.EscapeDataString("oauth_nonce") + "=" + QUOTE + Uri.EscapeDataString(AuthorizeApp.g_unique_nonce_string) + QUOTE_COMMA +
                   // Uri.EscapeDataString("oauth_callback") + "=" + QUOTE + Uri.EscapeDataString("oob") + QUOTE_COMMA +
                    Uri.EscapeDataString("oauth_signature") + "=" + QUOTE + Uri.EscapeDataString(signature_string) + QUOTE_COMMA +
                    Uri.EscapeDataString("oauth_signature_method") + "=" + QUOTE + Uri.EscapeDataString(AuthorizeApp.gOAUTH_SIGNATURE_METHOD) + QUOTE_COMMA +
                    Uri.EscapeDataString("oauth_timestamp") + "=" + QUOTE + Uri.EscapeDataString(AuthorizeApp.gTIME_STAMP) + QUOTE_COMMA +
                
                    Uri.EscapeDataString("oauth_version") + "=" + QUOTE + Uri.EscapeDataString(AuthorizeApp.gOAUTH_VERSION) + QUOTE;

            return Authorization;
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            Uri test = new Uri("https://api.twitter.com/1.1/oauth/request_token");

            HttpWebRequest TwRequest = (HttpWebRequest)WebRequest.Create(test);
            HttpWebResponse TwResponse;

            TwRequest.Method = "POST";
            TwRequest.ContentType = "application/x-www-form-urlencoded";

            TwitterApp MyApp = new TwitterApp();
            Authorize RestAuthorize = new Authorize();

            string auth_header = RestAuthorize.GetAuthorizationHeader(MyApp);
            auth_header = "Oauth "+ auth_header;

            TwRequest.Headers.Add("Authorization", auth_header);
            byte[] post_data = System.Text.Encoding.ASCII.GetBytes(auth_header);
          
              

            StreamWriter writer = new StreamWriter(TwRequest.GetRequestStream());
   
            
            Console.WriteLine(TwRequest.Headers.ToString());
           
            Stream newStream = TwRequest.GetRequestStream();
            var transmit =System.Text.Encoding.ASCII.GetBytes("oauth_callback" +"="+ "\""+ "oob"+ "\"");
            newStream.Write(transmit, 0, transmit.Length);
            newStream.Close();
      
            try
            {
                TwResponse = (HttpWebResponse)TwRequest.GetResponse();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }


        }
    }

}

hi my tweet message like asp.net vb.net and microsoft.net,
because of URL shorting length i was not able to tweet 140 characters will you please suggest me where i need to change URL length using twitter oauth api.