Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Super Contributor
Posts: 257
Registered: ‎05-05-2011
My Device: 9700
My Carrier: AT&T
Accepted Solution

twitter integration

Hi everyone,

 I need to implement some twitter functionality in my app, that is, to post tweets. My app is a typical charity application, so people can tweet that they've just donated some amount of money. I was given oAuthKey and oAuthSecret. But as I understand, we need xAuth ones? https://dev.twitter.com/docs/auth says that it's difficult to handle callback and therefore use oAuth. Also, examples of code on this forum, TwiAPI ME are all using xAuth. So my question is - should I ask people to request xAuth or it still possible to use oAuth to tweet?

 

Developer
Posts: 526
Registered: ‎05-17-2009
My Device: 9900
My Carrier: ATT

Re: twitter integration

Where is this "TwiAPI ME" library? If it is one of the j2me libraries I remember, I think it was done with basic auth and never upgraded to support OAuth but I could be wrong.

 

Also, make sure you understand the difference between xAuth and oAuth. Both are methods to get an access token, just the flow that you go about getting the token is different. Both use the consumer key and secret. With oAuth you have to send the user to a browser(browser field) to authorize your app and get a pin number that they then return to your app and enter the pin for you to finish the flow and get the token. xAuth just skips the browser step and makes you enter a user name and password to pass to twitter and then return a token. You wold never store the username and password.

 

I would use this library for oauth, and then a method like this to make a call to the twitter api (in the auth case accessToken would be null, and query params would have the username/password as specified by the docs). Your endpoint should be https://api.twitter.com/oauth/access_token

 

public String accessProtectedResource(String endpoint, AccessToken accessToken, Hashtable queryParams, String httpMethod) throws OAuthServiceProviderException, IOException, Exception {
        String responseString=null;
        OAuthMessage requestMessage = new OAuthMessage();
        requestMessage.setRequestMethod(httpMethod);
        requestMessage.setRequestURL(endpoint);
        requestMessage.setConsumerKey(config.getKey());
        if(accessToken != null){
        requestMessage.setToken(accessToken.getToken());
        requestMessage.setTokenSecret(accessToken.getSecret());
        }
        if (queryParams==null) {
            requestMessage.setAttitionalProperties(new Hashtable());
        } else {
            requestMessage.setAttitionalProperties(queryParams);
        }
        requestMessage.createSignature(signatureMethod, config.getSecret());
        
        //System.out.println("Base String = "+requestMessage.signatureBaseString(accessToken.getSecret()));
        System.out.println("Authorization header = "+requestMessage.convertToHeaderParameters());
        System.out.println("Request parameters = "+requestMessage.getUrlParameters());
        String url=endpoint + "?" + requestMessage.getUrlParameters();
        System.out.println("Attempting to access "+url);
            
        if (OAuthMessage.METHOD_POST.equals(httpMethod))
        {
            HttpConnection c = null;
            OutputStream os = null;
            int rc;

            try {
                System.out.println("UTIL -- posting to "+url);
    			// Create ConnectionFactory
    			ConnectionFactory factory = new ConnectionFactory();
    			}
    			// use the factory to get a connection
    			ConnectionDescriptor conDescriptor = factory.getConnection(url);
    			if ( conDescriptor != null ) {
    			   // using the connection
    			   c = (HttpConnection) conDescriptor.getConnection();
    			} else {
    				Exception e = new Exception("Could not connect");
    				throw e;
    			}
                
                // Set the request method and headers
                c.setRequestMethod(HttpConnection.POST);
                c.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
                c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                c.setRequestProperty("Content-Length", "0");
                c.setRequestProperty("Authorization", requestMessage.convertToHeaderParameters());
                
                System.out.println("content-length" + url.length());
                // Getting the output stream may flush the headers
                os = c.openOutputStream();
                
                // Getting the response code will open the connection,
                // send the request, and read the HTTP response headers.
                // The headers are stored until requested.
                rc = c.getResponseCode();
                
                int len = c.getHeaderFieldInt("Content-Length", 0);
                //int len = (int)c.getLength();
                System.out.println("content-length="+len);
                
                byte[] data = Util.readFromHTTPConnection(c);
                responseString=new String(data);
            } catch (ClassCastException e) {
                throw new IllegalArgumentException("Not an HTTP URL");
            } finally {
                if (os != null)
                    os.close();
                if (c != null)
                    c.close();
            }
            if (rc != HttpConnection.HTTP_OK) {
                throw new OAuthServiceProviderException("HTTP response code: " + rc, rc, responseString);
            }

        } 
        
        return responseString;
    public String convertToHeaderParameters(String realm) {
    	OAuthParameterEncoder encoder = new OAuthParameterEncoder();
        String newLine = "\r\n";
        String encodedMessage = "OAuth ";

        encodedMessage += "realm=\"http://api.twitter.com/\", ";
        if (!"".equals(nonce)) {
            encodedMessage += "oauth_nonce=\"" + encoder.encode(nonce)+"\", ";
        }
        if (!"".equals(signatureMethod)) {
            encodedMessage += "oauth_signature_method=\"" + encoder.encode(signatureMethod)+"\", ";
        }
        if (!"".equals(timestamp)) {
            encodedMessage += "oauth_timestamp=\"" + encoder.encode(timestamp)+"\", ";
        }
        if (!"".equals(consumerKey)) {
            encodedMessage += "oauth_consumer_key=\"" + encoder.encode(consumerKey)+"\", ";
        }
        if (!"".equals(token) && token!=null) {
            encodedMessage += "oauth_token=\"" + encoder.encode(token)+"\", ";
        }
        if (!"".equals(signature)) {
            encodedMessage += "oauth_signature=\"" + encoder.encode(signature)+"\", ";
        }
        if (!"".equals(version)) {
            encodedMessage += "oauth_version=\"" + encoder.encode(version)+"\"";
        }
        return encodedMessage;
    }

 

    }    

 

Like all of my posts
Super Contributor
Posts: 257
Registered: ‎05-05-2011
My Device: 9700
My Carrier: AT&T

Re: twitter integration

thank you for the response, but I still have questions  - how do I get this accessToken? And what to pass in the hashtable queryParams? I'm sorry if these are silly questions, but I've searched this forum for oAuth authorization and found no useful results so far.

Developer
Posts: 526
Registered: ‎05-17-2009
My Device: 9900
My Carrier: ATT

Re: twitter integration

You use this code to make a call to the twitter access_token endpoint. Read the documentation here https://dev.twitter.com/docs/oauth/xauth

The hashtable is just the arguments for the twitter api call that you are making
Like all of my posts
Super Contributor
Posts: 257
Registered: ‎05-05-2011
My Device: 9700
My Carrier: AT&T

Re: twitter integration

[ Edited ]

Ok, I'm working on OAuth now..So I use code from this thread:

http://supportforums.blackberry.com/t5/Java-Development/OAuth-OAuth-workaround/td-p/392777/page/2

 

Now I face strange results: I pass this string

https://api.twitter.com/oauth/request_token?
oauth_consumer_key=8hb8Do3i9oGLhF8y4KsJhQ
&oauth_nonce=2768120109006250293
&oauth_signature=30GW%2BE7HvSQhbYTxF9LKl11TRBk%3D
&oauth_signature_method=HMAC-SHA1
&oauth_timestamp=1317749766
&oauth_version=1.0

 in PC browser and successfully get token and secret, but the same string returns 401 error from BB browser and from requestToken(). I checked uppercase letters but still no good results. What should I do in this case?

 

Request string is:

GET&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_consumer_key%3D8hb8Do3i9oGKhF8y4KsJhQ%26oauth_nonce%3D2363003576654276833%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1317774879%26oauth_version%3D1.0

 

Super Contributor
Posts: 257
Registered: ‎05-05-2011
My Device: 9700
My Carrier: AT&T

Re: twitter integration

[ Edited ]

Ok, finally I got 200 response codeSmiley Happy Just follow the code on this page

http://supportforums.blackberry.com/t5/Java-Development/OAuth-OAuth-workaround/td-p/392777/page/6

 

also, don't forget to check that you have upper case letters in hex array in URLUTF8Encoder.

 

I attached classes I used, so I hope it'll save somebody hours of searching.