EzDevInfo.com

signpost

A light-weight client-side OAuth library for Java

Problem with OAuth, Twitter and Android: fails in http-communication with the server

Does anyone have a working example of OAuth authentication for twitter with Android? I have tried to use both Twitter4J and SignPost, but I get very strange errors, saying twitter.com is an unknown host. I have understod that there is a problem (under Google Android) with the SignPost library and Android and according to the project's home-page, the CommonsHttpOAuth* classes shall work.

Here is my SignPost:

private void getReqTokenAndAuthenticateUsingSignPost() {
    String callbackUrl = "twitter-test:///";
    CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY,
            CONSUMER_SECRET);
    CommonsHttpOAuthProvider provider = new CommonsHttpOAuthProvider(
            "http://twitter.com/oauth/request_token", "http://twitter.com/oauth/access_token",
            "http://twitter.com/oauth/authorize");

    String tokenStr = consumer.getToken();
    String tokenSecretStr = consumer.getTokenSecret();

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    Editor edit = preferences.edit();
    edit.putString(REQ_TOKEN, tokenStr);
    edit.putString(REQ_TOKEN_SECRET, tokenSecretStr);

    try {
        String authUrl = provider.retrieveRequestToken(consumer, callbackUrl);
        Uri authenticationUri = Uri.parse(authUrl);
        startActivity(new Intent(Intent.ACTION_VIEW, authenticationUri));
    } catch (OAuthMessageSignerException e) {
        e.printStackTrace();
    } catch (OAuthNotAuthorizedException e) {
        e.printStackTrace();
    } catch (OAuthExpectationFailedException e) {
        e.printStackTrace();
    } catch (OAuthCommunicationException e) {
        e.printStackTrace();
    }

}

and here is my code for Twitter4J:

private void getReqTokenAndAuthenticateUsingTwitter4J() {

    String callbackUrl = "twitter-test:///";
    try {
        // Prepare a request token, based on consumer key and consumer
        // secret
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(CONSUMER_KEY);
        builder.setOAuthConsumerSecret(CONSUMER_SECRET);
        Configuration cfg = builder.build();
        Twitter t = new TwitterFactory(cfg).getInstance();

        RequestToken requestToken = t.getOAuthRequestToken(callbackUrl);
        String tokenStr = requestToken.getToken();
        String tokenSecretStr = requestToken.getTokenSecret();

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        Editor edit = preferences.edit();
        edit.putString(REQ_TOKEN, tokenStr);
        edit.putString(REQ_TOKEN_SECRET, tokenSecretStr);
        if (edit.commit()) {
            // Launch the browser for authentication in twitter's web-gui
            Uri authenticationUri = Uri.parse(requestToken.getAuthenticationURL());
            startActivity(new Intent(Intent.ACTION_VIEW, authenticationUri));
        }
    } catch (TwitterException e) {
        e.printStackTrace();
    }
}

and yes, I have a manifest with Internet permission and an intent filter for the callback-url. Here is the output from logcat when running the SignPost code:

W/System.err(  779): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: twitter.com
W/System.err(  779):    at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214)
W/System.err(  779):    at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
W/System.err(  779):    at com.examples.twitterimages.TwitterImagesActivity.getReqTokenAndAuthenticateUsingSignPost(TwitterImagesActivity.java:109)
W/System.err(  779):    at com.examples.twitterimages.TwitterImagesActivity.onCreate(TwitterImagesActivity.java:64)
W/System.err(  779):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
W/System.err(  779):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)
W/System.err(  779):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)
W/System.err(  779):    at android.app.ActivityThread.access$1500(ActivityThread.java:121)
W/System.err(  779):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
W/System.err(  779):    at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err(  779):    at android.os.Looper.loop(Looper.java:123)
W/System.err(  779):    at android.app.ActivityThread.main(ActivityThread.java:3701)
W/System.err(  779):    at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err(  779):    at java.lang.reflect.Method.invoke(Method.java:507)
W/System.err(  779):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
W/System.err(  779):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
W/System.err(  779):    at dalvik.system.NativeStart.main(Native Method)
W/System.err(  779): Caused by: java.net.UnknownHostException: twitter.com
W/System.err(  779):    at java.net.InetAddress.lookupHostByName(InetAddress.java:506)
W/System.err(  779):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
W/System.err(  779):    at java.net.InetAddress.getAllByName(InetAddress.java:256)
W/System.err(  779):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136)
W/System.err(  779):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
W/System.err(  779):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
W/System.err(  779):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
W/System.err(  779):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
W/System.err(  779):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
W/System.err(  779):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
W/System.err(  779):    at oauth.signpost.commonshttp.CommonsHttpOAuthProvider.sendRequest(CommonsHttpOAuthProvider.java:64)
W/System.err(  779):    at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:177)
W/System.err(  779):    ... 16 more

and here is the output when running the Twitter4J code:

W/System.err(  817): api.twitter.comRelevant discussions can be on the Internet at:
W/System.err(  817):    http://www.google.co.jp/search?q=6c607809 or
W/System.err(  817):    http://www.google.co.jp/search?q=0f1d8134
W/System.err(  817): TwitterException{exceptionCode=[6c607809-0f1d8134 6c607809-0f1d810a], statusCode=-1, retryAfter=0, rateLimitStatus=null, version=2.2.1}
W/System.err(  817):    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:204)
W/System.err(  817):    at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
W/System.err(  817):    at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:102)
W/System.err(  817):    at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:108)
W/System.err(  817):    at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:271)
W/System.err(  817):    at com.examples.twitterimages.TwitterImagesActivity.getReqTokenAndAuthenticateUsingTwitter4J(TwitterImagesActivity.java:136)
W/System.err(  817):    at com.examples.twitterimages.TwitterImagesActivity.onCreate(TwitterImagesActivity.java:64)
W/System.err(  817):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
W/System.err(  817):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)
W/System.err(  817):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)
W/System.err(  817):    at android.app.ActivityThread.access$1500(ActivityThread.java:121)
W/System.err(  817):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
W/System.err(  817):    at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err(  817):    at android.os.Looper.loop(Looper.java:123)
W/System.err(  817):    at android.app.ActivityThread.main(ActivityThread.java:3701)
W/System.err(  817):    at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err(  817):    at java.lang.reflect.Method.invoke(Method.java:507)
W/System.err(  817):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
W/System.err(  817):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
W/System.err(  817):    at dalvik.system.NativeStart.main(Native Method)
W/System.err(  817): Caused by: java.net.UnknownHostException: api.twitter.com
W/System.err(  817):    at java.net.InetAddress.lookupHostByName(InetAddress.java:506)
W/System.err(  817):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
W/System.err(  817):    at java.net.InetAddress.getAllByName(InetAddress.java:256)
W/System.err(  817):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:69)
W/System.err(  817):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48)
W/System.err(  817):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:322)
W/System.err(  817):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
W/System.err(  817):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:285)
W/System.err(  817):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:267)
W/System.err(  817):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:205)
W/System.err(  817):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:614)
W/System.err(  817):    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:162)
W/System.err(  817):    ... 19 more

Have anybody resolved this? I'm stuck here. I can get the code to run as a Java SE program, but it fails on android...

// Jonas


Source: (StackOverflow)

Android Tumblr oAuth Confusion

I'm trying to implement the Tumblr API in an Android app. I'm really getting stuck with authorizing a user so that they can do things such as post and view their dashboard. I don't really understand oAuth, and the Tumblr API documentation sort of skips right over it. I have no idea if I'm supposed to prompt the user for their credentials, or what to do with those once I have them, or anything like that. I added the Signpost library to my project, but I've been scratching my head since then. Anybody familiar with oAuth on Android who would care to fill me in? Thanks!


Source: (StackOverflow)

Advertisements

HttpURLConnection.getResponseCode() returns -1 on second invocation

I seem to be running into a peculiar problem on Android 1.5 when a library I'm using (signpost 1.1-SNAPSHOT), makes two consecutive connections to a remote server. The second connection always fails with a HttpURLConnection.getResponseCode() of -1

Here's a testcase that exposes the problem:

// BROKEN
public void testDefaultOAuthConsumerAndroidBug() throws Exception {
    for (int i = 0; i < 2; ++i) {
        final HttpURLConnection c = (HttpURLConnection) new URL("https://api.tripit.com/oauth/request_token").openConnection();
        final DefaultOAuthConsumer consumer = new DefaultOAuthConsumer(api_key, api_secret, SignatureMethod.HMAC_SHA1);
        consumer.sign(c);                             // This line...
        final InputStream is = c.getInputStream();
        while( is.read() >= 0 ) ;                     // ... in combination with this line causes responseCode -1 for i==1 when using api.tripit.com but not mail.google.com
        assertTrue(c.getResponseCode() > 0);
    }
}

Basically, if I sign the request and then consume the entire input stream, the next request will fail with a resultcode of -1. The failure doesn't seem to happen if I just read one character from the input stream.

Note that this doesn't happen for any url -- just specific urls such as the one above.

Also, if I switch to using HttpClient instead of HttpURLConnection, everything works fine:

// WORKS
public void testCommonsHttpOAuthConsumerAndroidBug() throws Exception {
    for (int i = 0; i < 2; ++i) {
        final HttpGet c = new HttpGet("https://api.tripit.com/oauth/request_token");
        final CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(api_key, api_secret, SignatureMethod.HMAC_SHA1);
        consumer.sign(c);
        final HttpResponse response = new DefaultHttpClient().execute(c);
        final InputStream is = response.getEntity().getContent();
        while( is.read() >= 0 ) ;
        assertTrue( response.getStatusLine().getStatusCode() == 200);
    }
}

I've found references to what seems to be a similar problem elsewhere, but so far no solutions. If they're truly the same problem, then the problem probably isn't with signpost since the other references make no reference to it.

Any ideas?


Source: (StackOverflow)

OAuth login with Google Apps Engine endpoint stopped working

I have a desktop Java application that communicates with a GAE server. The client application signs in to the server using OAuth 1.0 with signpost via the provided endpoints (appname.appengine.com/_ah/OAuthGetAccessToken and the like) with consumerkey and consumersecret set to "anonymous" and scope set to the GAE domain. The login process appears to be working fine:

  1. Retrieve Request Token
  2. Let the user visit the resulting authentication URL
  3. Ask user for verification code
  4. Retrieve Access Token

At this point, I have a seemingly valid token and token secret. If I use these to sign a request to the GAE server, I get an OAuthRequestException when identifying the user:

OAuthService oauthService = OAuthServiceFactory.getOAuthService();
try {
    user = oauthService.getCurrentUser();
    if (user != null) {
        ri.userName = user.getEmail();
    }
} catch (OAuthRequestException t) {
    t.printStackTrace();
}

This used to work fine until this morning. I am using a modified version of the Chrome to Phone GAE backend. I noticed that Chrome to Phone is having the same issue: I cannot login to the service anymore, so I don't believe this is an error on the client side. Logins don't show up in the Google Connected Sites, Apps, and Services console. Here is a link to the affected line in Chrome to Phone's GAE service: Chrome2Phone affected source.

I already tried registering the application in the Google API console and provided comsumer key and secret, with the same result.


Source: (StackOverflow)

OAuth with Android

I am attempting to access the Yelp API. I have obtained my keys and have read about 40 articles explaining what I need to do and I have attempted everything. The key and what not are valid. I am getting the following:

05-16 17:39:54.955: E/AndroidRuntime(538): java.lang.NoClassDefFoundError: oauth.signpost.commonshttp.CommonsHttpOAuthConsumer

I have imported the commons-codec-1.6 jar, the signpost-commonshttp4-1.2.1.2.jar, and the signpost-core-1.2.1.2.jar.

I am still getting the error message. Any help?

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;


/**
 * Example for accessing the Yelp API.
 */
public class Yelp {
  private String consumerKey = "";
  private String consumerSecret = "";
  private String token = "";
  private String tokenSecret = "";

  /**
   * Search with term and location.
   *
   * @param term Search term
   * @param latitude Latitude
   * @param longitude Longitude
   * @return JSON string response
   */
  public String search(String term, double latitude, double longitude) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException {



    try {
        OAuthConsumer myConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
        myConsumer.setTokenWithSecret(token, tokenSecret);

        String urlToPost = "http://api.yelp.com/v2/search";
        Map<String, String> myMap = new HashMap<String, String>();
        myMap.put(OAuth.OAUTH_CONSUMER_KEY, consumerKey);
        myMap.put(OAuth.OAUTH_TOKEN, token);
        myMap.put(OAuth.OAUTH_SIGNATURE_METHOD, "HMAC-SHA1");
        myMap.put(OAuth.OAUTH_SIGNATURE, tokenSecret);
        myMap.put(OAuth.OAUTH_TIMESTAMP, Long.toString(System.currentTimeMillis() / 1000L));
        myMap.put(OAuth.OAUTH_NONCE, "asdf");

        urlToPost = OAuth.addQueryParameters(urlToPost, myMap);

        HttpURLConnection myCon = (HttpURLConnection) (new URL(urlToPost)).openConnection();
        myConsumer.sign(myCon);

        myCon.connect();
        return myCon.getResponseMessage();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
  }
}

Source: (StackOverflow)

how to create issue using bitbucket API and singpost in java

I am trying to create new issue at bibucket, but i don't know how to work with http. I try many things but it stil dosen't work. This is one of my attempts:

URL url = new URL("https://api.bitbucket.org/1.0/repositories/" 
        + accountname + "/" + repo_slug + "/issues/"
        + "?title=test&content=testtest");

HttpsURLConnection request = (HttpsURLConnection) url.openConnection();       
request.setRequestMethod("POST");
consumer.sign(request);
request.connect();

I don't have a problem with GET requests. But here I don't know how to send parametrs and sign the message.

Here is documentation of API https://confluence.atlassian.com/display/BITBUCKET/issues+Resource#issuesResource-POSTanewissue

How to do this properly?


Source: (StackOverflow)

Oauth on android using signpost library

I try since a few days to connect one of my android app to an oauth service. I have found a few really good articles like http://blog.doityourselfandroid.com/2011/04/12/oauth-android-google-apis-client-library-java/ or marakana.com/forums/android/examples/312.html but even with those papers I can't manage to make It work.

Well, here is my current code packaged in a tar archive : http://braindead.fr/oauth-warrior.tar.gz

So the problem is that each time I attempt to retrieve an access token I got an OAuthCommunicationException (respectively line 26 and 39 of OAUthTokenValidator.java) after user validation on oauth server and url callback.

I anybody know why signopost/oauth does not accept to make this last call I'll be really grateful :)

Sincerely, Daroth


Source: (StackOverflow)

Yelp v2 API from Android using SignPost oauth libs says Signature Invalid

Trying to call from an android client, using the signpost oauth libs. I generated new APIv2 keys, but didn't seem to make a difference. The error I'm getting looks like:

{"error":{"text":"Signature was 
invalid","id":"INVALID_SIGNATURE","description":"Invalid signature. 
Expected signature base string: GET&http%3A%2F%2Fapi.yelp.com 
%2Fv2%2Fsearch&category_filter%3Drestaurants%2520food%26limit%3D10%26ll 
%3D37.422005%252C-122.084095%26oauth_consumer_key 
%3DPbSjw9p08To_XXXXXXXXZg%26oauth_nonce 
%3D-81097XXXXXXXX560239%26oauth_signature_method%3DHMAC- 
SHA1%26oauth_timestamp%3D129XXXX091%26oauth_token 
%3DARfbDXXXXXXXXlBHARTgygLkcMw9h8eW%26oauth_version%3D1.0%26offset 
%3D0%26radius_filter%3D300%26sort%3D0"}} 

I double checked, and all my token and secret values exactly match what's in the manage API screen. Code currently looks like this:

if (location != null) { 
        String lat = Double.toString(location.getLatitude()); 
        String lng = Double.toString(location.getLongitude()); 
        String category = "restaurants+food"; 
        String radius = "300"; 
        String limit = "10"; 
        String offset = "0"; 
        String sort = "0"; 
        try { 
                String query = String.format("http://api.yelp.com/v2/search?ll=%s, 
%s&category_filter=%s&radius_filter=%s&limit=%s&offset=%s&sort=%s", 
                                URLEncoder.encode(lat, ENCODING_SCHEME), 
                                URLEncoder.encode(lng, ENCODING_SCHEME), 
                                category, 
                                URLEncoder.encode(radius, ENCODING_SCHEME), 
                                URLEncoder.encode(limit, ENCODING_SCHEME), 
                                URLEncoder.encode(offset, ENCODING_SCHEME), 
                                URLEncoder.encode(sort, ENCODING_SCHEME)); 
                OAuthConsumer consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, 
CONSUMER_SECRET); 
                consumer.setTokenWithSecret(TOKEN, TOKEN_SECRET); 
                consumer.setMessageSigner(new HmacSha1MessageSigner()); 
                consumer.setSendEmptyTokens(true); 
                consumer.setSigningStrategy(new QueryStringSigningStrategy()); 
                String signedQuery = consumer.sign(query); 
                Log.i(getClass().getName(), signedQuery); 
                HttpGet request = new HttpGet(signedQuery); 
                HttpClient httpClient = new DefaultHttpClient(); 
                HttpResponse response = (HttpResponse) httpClient.execute(request); 
                HttpEntity entity = response.getEntity(); 
                String jsonResult = EntityUtils.toString(entity); 
                Log.i(getClass().getName(), jsonResult); 

Source: (StackOverflow)

jTwitter, oAuth, and Google App Engine. NoClassDefFoundError

I'm trying to use jTwitter to get an oauth instance to twitter with my consumer key/secret and access token/secret. This is well documented in the javadoc here. I have downloaded signpost, signpost-jetty, and the jtwitter library, but after deploying and running the servlet, I get a error java.lang.NoClassDefFoundError: winterwell/jtwitter/OAuthSignpostClient Eclipse isn't complaining about the class not being there, because it is there-- I can see it in the JAR file itself, which is in my project. So, I said forget it, I'll try out OAuthScribeClient instead, but this generated a VERY SIMILAR ERROR java.lang.NoClassDefFoundError: org/scribe/oauth/Token This one confuses me even further because I have the following code in my java file, and it compiles without error or warning:

import org.scribe.oauth.Token;
Token token = new Token("myaccesstokeninfo", "accesstokensecret");

Clearly, I'm missing something very fundamental, but I am at an absolute loss as to what it may be. Thanks.


Source: (StackOverflow)

Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth)

I am using signpost for OAuth to access data from a Magento server. I have read various tutorials on the same and I reach to the point where we open a browser so that user can enter his credentials. However, as per my requirement I have to automate this part.

Hence, user should not get the browser page. I have this set-up done on the server side (Magento), where I hit the URL and get returned to the call back page. I would like to do the same through my program in Android.

I have tried the below,

consumer = new CommonsHttpOAuthConsumer(KEY, Secret);
provider = new CommonsHttpOAuthProvider(OAUTH_INIT_URL,ACCESS_TOKEN_URL, AUTHORIZE_URL);                
try {
    provider.retrieveRequestToken(consumer, OAuth.OUT_OF_BAND);
    Log.d("Tokens" , consumer.getToken() + " -- " + consumer.getTokenSecret());
    }

and I get the request tokens. But I dont know how to bypass the next step. I tried directly accessing the AccessToken (stupid of me) provider.retrieveAccessToken(consumer, "myCallback://callback"); but no luck, it ends up in

oauth.signpost.exception.OAuthNotAuthorizedException: Authorization failed (server   replied with a 401). This can happen if the consumer key was not correct or the signatures did not match.

I would really appreciate any help, as I am stuck on this from last 3 days. Please tell me if I need to provide any more data.


Source: (StackOverflow)

Twitter API status update always returns "Incorrect signature"

I'm using Signpost as OAuth implementation for posting to Twitter. And implemented the GoogleAppEngineOAuthConsumer and GoogleAppEngineOAuthProvider classes, but since they're pretty trivial, so I'm not providing their sources here (yet).

Here's my authentication part, which seems to work just fine.

LoginServlet.java:

// fetching the request token
OAuthConsumer consumer = new GoogleAppEngineOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
OAuthProvider provider = new GoogleAppEngineOAuthProvider(REQUEST_TOKEN_URL, ACCESS_TOKEN_URL, AUTHORIZATION_URL);
String redirectUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
// cache the request token and request token secret
response.sendRedirect(redirectUrl);

CallbackServlet.java

// fetching the access token
String verifier = (String) req.getParameter("oauth_verifier");
// retrieve request token and request token secret from cache
OAuthConsumer consumer = new GoogleAppEngineOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
OAuthProvider provider = new GoogleAppEngineOAuthProvider(REQUEST_TOKEN_URL, 
consumer.setTokenWithSecret(token, tokenSecret);
provider.setOAuth10a(true);
provider.retrieveAccessToken(consumer, verifier);
// store access token and access token secret

And here's the actual problematic part.

TweetServlet.java

OAuthConsumer consumer = new GoogleAppEngineOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
// retrieve access token and access token secret from storage
consumer.setTokenWithSecret(accessToken, accessTokenSecret);
final HTTPRequest updateStatus = new HTTPRequest(new URL("http://api.twitter.com/1/statuses/update.json"), HTTPMethod.POST);
updateStatus.setPayload(("status=" + URLEncoder.encode(message, "UTF-8")).getBytes());
consumer.sign(updateStatus);
logger.debug(new String(URLFetchServiceFactory.getURLFetchService().fetch(updateStatus).getContent()));

Each and every time it results: {"request":"/1/statuses/update.json","error":"Incorrect signature"}.


Source: (StackOverflow)

How to send an image to a Javascript client using JSON from a Java server

I am working on Google Contacts API and I received all data and sending as string to JSON (javascript) but when I get an image from contacts I can receive image. How can I send it to JSON? How can send the image file to a URL? (Can I use signpost?)

if (photoLink.getEtag() != null) {
 GDataRequest request = myService.createLinkQueryRequest(photoLink);
 request.execute();                                                                                    
 // No Authentication header information  
 InputStream stream = request.getResponseStream();    
 Image image=  ImageIO.read(stream);
 }

Source: (StackOverflow)

Signpost OAuth on Android: how to re-create the Consumer between two succesive runs?

I'm succesfully using Signpost to authorize calls to protected resources in a Google account via OAuth.

However it seems a bit weird that the user has to go each and every time through Google and grant access. Is there a way of serializing the Consumer and recreating it so that re-authorization is not needed? I've tried keeping the tokens, secret and verifier in the shared preferences and setting them in the Consumer but I receive a OAuthExpectationFailedException.

Any ideas?


Source: (StackOverflow)

Yahoo OAuth on Android - 401 error

I'm trying to implement OAuth for Google, Twitter, Yahoo etc. on Android using the signpost libraries.

All of the above work fine, except Yahoo, which gives me a 401 error when trying to retrieve the Request Token. I've tried modifying my callback url to an http one, and even tried Out of Band authentication.

Does anyone have an idea on what I could be doing wrong ?

My code which requests for the OAuth Request Token using Signpost libraries is pasted below.

private static CommonsHttpOAuthConsumer yahooConsumer = new CommonsHttpOAuthConsumer(
        YAHOO_CONSUMER_KEY, YAHOO_CONSUMER_SECRET);
private static CommonsHttpOAuthProvider yahooProvider = new CommonsHttpOAuthProvider(
        YAHOO_REQUEST_URL, YAHOO_ACCESS_TOKEN_URL, YAHOO_AUTH_URL); 

and

String authURL = yahooProvider.retrieveRequestToken( yahooConsumer,YAHOO_REDIRECT_URL); startWebView(authURL);

EDIT:

Here's the output from the catched Exception :

08-21 00:18:10.935: WARN/System.err(3752): oauth.signpost.exception.OAuthNotAuthorizedException: Authorization failed (server replied with a 401). This can happen if the consumer key was not correct or the signatures did not match. 08-21 00:18:10.945: WARN/System.err(3752): at oauth.signpost.AbstractOAuthProvider.handleUnexpectedResponse(AbstractOAuthProvider.java:239) 08-21 00:18:10.945: WARN/System.err(3752): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:189) 08-21 00:18:10.955: WARN/System.err(3752): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)

Thanks,

Abhinav


Source: (StackOverflow)

OAuth 1.0 Requests with Retrofit in Android

I am trying to access a Magento REST API in my Android app, using Retrofit.

What have I tried:

But none of them have worked.

Retrofit 1.7 and OkHttp2.0RC2 don't work well with SignPost (at least the way the article suggest)

And when I downgrade for things to work, I get error HTTP 500 Error saying Internal Server Error

The same credentials work using REST Client plugin for Firefox.

Is there a working solution for implementing OAuth requests with Retrofit, or any other option?

Much thanks in advance.


Source: (StackOverflow)