2011-10-20 14 views
5

Ok, sto creando un client Tumblr per Android, sto provando e non riuscendo a far funzionare OAuth per circa una settimana. Ecco come sta andando:Android Tumblr Oauth-signpost 401

L'utente attiva l'app. Attività principale suCreate fa questo:

settings = getSharedPreferences(PREFS_NAME, 0); 
authToken=settings.getString("OauthToken", "none"); 
authTokenSecret=settings.getString("OauthSecret", "none"); 
if(authToken=="none" || authTokenSecret=="none"){ 
    Intent i = new Intent(getApplicationContext(),Authentication.class); 
    startActivity(i); 
} 

avvia un'attività di autenticazione che contiene una WebView. Tale attività ottiene correttamente il token di richiesta e invia WebView alla schermata di accesso di Tumblr. L'utente è invitato a consentire l'accesso ai propri dati da parte app, premono Consenti e il mio WebViewClient cattura la richiamata Url, e lo fa con esso:

String[] token = helper.getVerifier(url); 
      if (token != null) { 
       try { 
        String accessToken[] = helper.getAccessToken(token[1]); 
        editor.putString("OauthToken", accessToken[0]); 
        editor.putString("OauthSecret", accessToken[1]); 
        editor.commit(); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
      finish(); 

getAccessToken del classe helper e getVerifier simile a questa:

public String[] getVerifier(String myUrl) { 
    // extract the token if it exists 
    Uri uri = Uri.parse(myUrl); 
    if (uri == null) { 
     return null; 
    } 

    String token = uri.getQueryParameter("oauth_token"); 
    String verifier = uri.getQueryParameter("oauth_verifier"); 
    return new String[] { token, verifier }; 
} 

public String[] getAccessToken(final String verifier) 
     throws OAuthMessageSignerException, OAuthNotAuthorizedException, 
     OAuthExpectationFailedException, OAuthCommunicationException { 
    new Thread(new Runnable() { 
     public void run() { 
       try { 
        mProvider.retrieveAccessToken(mConsumer, verifier); 
       } catch (OAuthMessageSignerException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } catch (OAuthNotAuthorizedException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } catch (OAuthExpectationFailedException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } catch (OAuthCommunicationException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
     } 
    }).start(); 
    return new String[] { 
      mConsumer.getToken(), mConsumer.getTokenSecret() 
    }; 
} 

Poi ho finalmente tornare alla schermata principale dell'applicazione e cerco di fare il mio primo chiamata API, per ottenere i più recenti dieci messaggi su cruscotto dell'utente:

OAuthConsumer myConsumer = new CommonsHttpOAuthConsumer(MainView.authToken, MainView.authTokenSecret); 
      HttpGet request = new HttpGet("http://api.tumblr.com/v2/user/dashboard?limit=10"); 
      myConsumer.sign(request); 
      HttpClient httpClient = new DefaultHttpClient(); 
      HttpResponse response = httpClient.execute(request); 
      HttpEntity entity = response.getEntity(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); 
      String line; 
      while ((line = reader.readLine()) != null) { 
       builder.append(line); 
      } 

Tuttavia, invece di ottenere una bella risposta JSON come dovrei essere, sto ottenendo questo:

10-20 16:36:18.110: D/Result(22817): {"meta":{"status":401,"msg":"Not Authorized"},"response":[]} 

Allora, dove ho sbagliato? Grazie

+1

Ricevo lo stesso identico problema con il tentativo di utilizzare i metodi API che richiedono richieste POST tuttavia, le richieste GET sembrano funzionare correttamente. Sto iniziando a chiedermi se la loro API è un po 'squilibrata. –

+0

Quale versione di Android stai sviluppando? – NotACleverMan

+0

Solo a nido d'ape. – Nick

risposta

2

Ho utilizzato con successo la libreria di segnalazioni con HttpCommons di Appache GET/POST/PUT.

In primo luogo, ho lanciato il WebView a scopo di accesso, utilizzando il seguente codice (ActivityLogin.java):

private static CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(AppConfig.CONSUMER_KEY, AppConfig.CONSUMER_SECRET); 
private static OAuthProvider provider = new DefaultOAuthProvider (AppConfig.requestURL, AppConfig.accessURL, AppConfig.authURL); 

private void logMeIn() throws ...{ 
    String authUrl = provider.retrieveRequestToken(consumer,AppConfig.CALLBACK_URL); 
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl))); 
} 

Poi, ho usato onNewIntent(Intent) per ricevere i callback OAuth dal precedentemente lanciato Activity:

AppConfig.java pezzo di codice presentato:

/** OAuth Authorization URL */ 
public static final String authURL = mainOAuthUrl+"/authorize/?theme=android"; 

/** OAuth Request URL */ 
public static final String requestURL = mainOAuthUrl+"/request/token/"; 

/** OAuth Access URL  */ 
public static final String accessURL = mainOAuthUrl+"/access/token/"; 

/** OAuth CALLback URL*/ 
public static final String CALLBACK_URL = "yourapp://twitt"; 

ActivityLogin.java codice snipet:

protected void onNewIntent(Intent intent) { 
    Uri uri = intent.getData(); 
    if (uri != null && uri.toString().startsWith(AppConfig.CALLBACK_URL)) { 
     String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER); 

     provider.retrieveAccessToken(consumer, verifier); 
     Data.OAuthAccessKey = consumer.getToken(); 
     Data.OAuthAccessSecret = consumer.getTokenSecret(); 
    } 

} 

E poi, il mio codice di connessione sembra che:

public HttpResponse sampleOauthConnect(String url) throws ...{ 

    /** setup some connection params */ 
    HttpContext context = new BasicHttpContext(); 

    HttpRequestBase request = new HttpGet(url); 

    if (Data.OAuthConsumer == null) 
     Data.OAuthConsumer = new CommonsHttpOAuthConsumer(AppConfig.CONSUMER_KEY, AppConfig.CONSUMER_SECRET); 

    if (Data.OAuthAccessKey == null || Data.OAuthAccessSecret == null) 
     throw new LoginErrorException(LoginErrorException.NOT_LOGGED_IN); 

    Data.OAuthConsumer.setTokenWithSecret(Data.OAuthAccessKey, Data.OAuthAccessSecret); 

    try { 
     Data.OAuthConsumer.sign(request); 
    } catch (OAuthMessageSignerException e) { 
     throw new LoginErrorException(LoginErrorException.OAUTH_EXCEPTION, e); 
    } catch (OAuthExpectationFailedException e) { 
     throw new LoginErrorException(LoginErrorException.OAUTH_EXCEPTION, e); 
    } catch (OAuthCommunicationException e) { 
     throw new LoginErrorException(LoginErrorException.OAUTH_EXCEPTION, e); 
    } 

    HttpClient client = new DefaultHttpClient(); 

    /** finally execute this request */ 
    return client.execute(request, context); 
} 

forse ho perso qualcosa durante copia-incolla, dimmi solo se questa soluzione funzionerà per voi. Sto usando il monoposto 1.2.1.1

+0

Non ho tempo di testare il tuo codice adesso o anche entro un paio di giorni, ma dal momento che la taglia si è esaurita e sembra un post completo molto utile, hai vinto! Grazie, scoprirò se funziona davvero dopo – Nick

+0

Tieni presente che io uso due coppie di chiavi proprio lì: 'AppConfig.CONSUMER_KEY, AppConfig.CONSUMER_SECRET' (che sono memorizzati nell'app) e' Data.OAuthAccessKey, Data.OAuthAccessSecret' che sono generati dal server. – Kocus

+0

ottiene la stessa risposta non autorizzata: {"meta": { "status": 401, "msg": "Not Authorized"}, "response": []} – DcodeChef

1

Attualmente, Tumblr non supporta MultipartEntity, quindi è necessario utilizzare NameValuePairs per aggiungere parametri.

Se si desidera pubblicare una foto, è necessario convertire tale foto in un ARRAY e URL lo codifica!

+0

Problema di fronte alla pubblicazione di foto. Cosa intendi dicendo "... converti quella foto in un ARRAY e l'URL lo codifica"? Potresti fornire qualche frammento di codice. –

+0

La biblioteca di Tumbler (Jumblr) utilizza i moduli multipart: https://github.com/tumblr/jumblr/blob/master/src/main/java/com/tumblr/jumblr/request/MultipartConverter.java – Jabari

Problemi correlati