public String normalizeRequestParameters() {
    if (requestParameters == null) {
      return "";
    }
    StringBuilder stringbuilder = new StringBuilder();
    Iterator iterator = requestParameters.keySet().iterator();
    for (int i = 0; iterator.hasNext(); i++) {
      String s = (String) iterator.next();
      if ("oauth_signature".equals(s) || "realm".equals(s)) {
        continue;
      }
      if (i > 0) {
        stringbuilder.append("&");
      }
      stringbuilder.append(requestParameters.getAsQueryString(s));
    }

    return stringbuilder.toString();
  }
示例#2
0
  /**
   * Normalizes the set of request parameters this instance was configured with, as per OAuth spec
   * section 9.1.1.
   *
   * @param parameters the set of request parameters
   * @return the normalized params string
   * @throws IOException
   */
  public String normalizeRequestParameters() throws IOException {
    if (requestParameters == null) {
      return "";
    }

    StringBuilder sb = new StringBuilder();
    Iterator<String> iter = requestParameters.keySet().iterator();

    for (int i = 0; iter.hasNext(); i++) {
      String param = iter.next();

      if (OAuth.OAUTH_SIGNATURE.equals(param) || "realm".equals(param)) {
        continue;
      }

      if (i > 0) {
        sb.append("&");
      }

      sb.append(requestParameters.getAsQueryString(param));
    }
    return sb.toString();
  }
  private void getOAuthToken() {
    /*
    Android users: Do NOT use the DefaultOAuth* implementations on Android, since there's a bug
    in Android's java.net.HttpURLConnection that keeps it from working with some service
    providers.

    Instead, use the CommonsHttpOAuth* classes, since they are meant to be used with
    Apache Commons HTTP (that's what Android uses for HTTP anyway).
     */
    // fatsecret_consumer_key = REST API Consumer Key, fatsecret_consumer_secret = REST API Shared
    // Secret
    final OAuthConsumer consumer =
        new CommonsHttpOAuthConsumer(
            getString(R.string.fatsecret_consumer_key),
            getString(R.string.fatsecret_consumer_secret));
    consumer.setMessageSigner(new HmacSha1MessageSigner());
    consumer.setSigningStrategy(new QueryStringSigningStrategy());

    HttpParameters requestTokenRequestParams = new HttpParameters();
    requestTokenRequestParams.put("oauth_callback", OAuth.OUT_OF_BAND);
    consumer.setAdditionalParameters(requestTokenRequestParams);

    try {
      String signedRequestTokenRequestUrl =
          consumer.sign("http://www.fatsecret.com/oauth/request_token");

      Log.d(TAG, "Signed request_token URL = " + signedRequestTokenRequestUrl);

      HttpURLConnection requestTokenUrlConnection =
          (HttpURLConnection) new URL(signedRequestTokenRequestUrl).openConnection();
      HttpParameters requestTokenResponseParams =
          OAuth.decodeForm(requestTokenUrlConnection.getInputStream());
      final String requestToken = requestTokenResponseParams.getFirst(OAuth.OAUTH_TOKEN);
      final String requestSecret = requestTokenResponseParams.getFirst(OAuth.OAUTH_TOKEN_SECRET);
      Log.d(TAG, "Request token = " + requestToken);
      Log.d(TAG, "Token secret = " + requestSecret);

      final String authorizeUrl =
          "http://www.fatsecret.com/oauth/authorize?oauth_token=" + requestToken;
      Log.d(TAG, "Authorize URL = " + authorizeUrl);
      runOnUiThread(
          new Runnable() {
            @Override
            public void run() {
              final Dialog authDialog = new Dialog(LoginActivity_FatSecret.this);
              authDialog.setContentView(R.layout.auth_dialog);
              WebView web = (WebView) authDialog.findViewById(R.id.webv);
              web.getSettings().setJavaScriptEnabled(true);
              web.loadUrl(authorizeUrl);
              web.setWebViewClient(
                  new WebViewClient() {
                    @Override
                    public void onPageStarted(WebView view, String url, Bitmap favicon) {
                      super.onPageStarted(view, url, favicon);
                    }

                    @Override
                    public void onPageFinished(WebView view, String url) {
                      super.onPageFinished(view, url);
                      Log.d(TAG, "URL = " + url);
                      if (url.contains("postVerify")) {
                        Uri uri = Uri.parse(url);
                        final String verifyCode = uri.getQueryParameter("postVerify");
                        Log.i(TAG, "VERIFY : " + verifyCode);
                        authDialog.dismiss();

                        runOnUiThread(
                            new Runnable() {
                              @Override
                              public void run() {
                                final ProgressDialog progressDialog =
                                    new ProgressDialog(LoginActivity_FatSecret.this);
                                progressDialog.setIndeterminate(true);
                                progressDialog.setMessage("Fetching access token...");
                                progressDialog.show();

                                new Thread(
                                        new Runnable() {
                                          @Override
                                          public void run() {
                                            consumer.getRequestParameters().clear();
                                            HttpParameters authTokenRequestParams =
                                                new HttpParameters();
                                            authTokenRequestParams.put("oauth_token", requestToken);
                                            authTokenRequestParams.put(
                                                "oauth_verifier", verifyCode);
                                            consumer.setAdditionalParameters(
                                                authTokenRequestParams);
                                            consumer.setTokenWithSecret(
                                                requestToken, requestSecret);

                                            try {
                                              String signedAccessTokenUrl =
                                                  consumer.sign(
                                                      "http://www.fatsecret.com/oauth/access_token");
                                              Log.d(
                                                  TAG,
                                                  "Signed access_token URL = "
                                                      + signedAccessTokenUrl);
                                              HttpURLConnection accessTokenUrlConnection =
                                                  (HttpURLConnection)
                                                      new URL(signedAccessTokenUrl)
                                                          .openConnection();
                                              HttpParameters accessTokenResponseParams =
                                                  OAuth.decodeForm(
                                                      accessTokenUrlConnection.getInputStream());

                                              String token =
                                                  accessTokenResponseParams.getFirst(
                                                      OAuth.OAUTH_TOKEN);
                                              String secret =
                                                  accessTokenResponseParams.getFirst(
                                                      OAuth.OAUTH_TOKEN_SECRET);
                                              prefs
                                                  .edit()
                                                  .putString(
                                                      FatSecretUtils.OAUTH_ACCESS_TOKEN_KEY, token)
                                                  .putString(
                                                      FatSecretUtils.OAUTH_ACCESS_SECRET_KEY,
                                                      secret)
                                                  .apply();

                                              Intent home =
                                                  new Intent(
                                                      LoginActivity_FatSecret.this,
                                                      SearchFood.class);
                                              startActivity(home);
                                              finish();
                                            } catch (OAuthMessageSignerException e) {
                                              e.printStackTrace();
                                            } catch (OAuthExpectationFailedException e) {
                                              e.printStackTrace();
                                            } catch (OAuthCommunicationException e) {
                                              e.printStackTrace();
                                            } catch (MalformedURLException e) {
                                              e.printStackTrace();
                                            } catch (IOException e) {
                                              e.printStackTrace();
                                            } finally {
                                              runOnUiThread(
                                                  new Runnable() {
                                                    @Override
                                                    public void run() {
                                                      loginButton.setEnabled(true);
                                                      progressDialog.dismiss();
                                                    }
                                                  });
                                            }
                                          }
                                        })
                                    .start();
                              }
                            });
                      } else if (url.contains("error")) {
                        Log.i(TAG, "authorize error");
                        Toast.makeText(getApplicationContext(), "Error Occured", Toast.LENGTH_SHORT)
                            .show();
                        runOnUiThread(
                            new Runnable() {
                              @Override
                              public void run() {
                                loginButton.setEnabled(true);
                                authDialog.dismiss();
                              }
                            });
                      }
                    }
                  });

              authDialog.setTitle("Authorize FatSecret");
              authDialog.setCancelable(true);
              authDialog.show();
            }
          });
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (OAuthExpectationFailedException e) {
      e.printStackTrace();
    } catch (OAuthCommunicationException e) {
      e.printStackTrace();
    } catch (OAuthMessageSignerException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /**
   * Implemented by subclasses. The responsibility of this method is to contact the service provider
   * at the given endpoint URL and fetch a request or access token. What kind of token is retrieved
   * solely depends on the URL being used.
   *
   * <p>Correct implementations of this method must guarantee the following post-conditions:
   *
   * <ul>
   *   <li>the {@link OAuthConsumer} passed to this method must have a valid {@link
   *       OAuth#OAUTH_TOKEN} and {@link OAuth#OAUTH_TOKEN_SECRET} set by calling {@link
   *       OAuthConsumer#setTokenWithSecret(String, String)}
   *   <li>{@link #getResponseParameters()} must return the set of query parameters served by the
   *       service provider in the token response, with all OAuth specific parameters being removed
   * </ul>
   *
   * @param consumer the {@link OAuthConsumer} that should be used to sign the request
   * @param endpointUrl the URL at which the service provider serves the OAuth token that is to be
   *     fetched
   * @param additionalParameters you can pass parameters here (typically OAuth parameters such as
   *     oauth_callback or oauth_verifier) which will go directly into the signer, i.e. you don't
   *     have to put them into the request first, just so the consumer pull them out again. Pass
   *     them sequentially in key/value order.
   * @throws OAuthMessageSignerException if signing the token request fails
   * @throws OAuthCommunicationException if a network communication error occurs
   * @throws OAuthNotAuthorizedException if the server replies 401 - Unauthorized
   * @throws OAuthExpectationFailedException if an expectation has failed, e.g. because the server
   *     didn't reply in the expected format
   */
  protected void retrieveToken(
      OAuthConsumer consumer, String endpointUrl, String... additionalParameters)
      throws OAuthMessageSignerException, OAuthCommunicationException, OAuthNotAuthorizedException,
          OAuthExpectationFailedException {
    Map<String, String> defaultHeaders = getRequestHeaders();

    if (consumer.getConsumerKey() == null || consumer.getConsumerSecret() == null) {
      throw new OAuthExpectationFailedException("Consumer key or secret not set");
    }

    HttpRequest request = null;
    HttpResponse response = null;
    try {
      request = createRequest(endpointUrl);
      for (String header : defaultHeaders.keySet()) {
        request.setHeader(header, defaultHeaders.get(header));
      }
      if (additionalParameters != null) {
        HttpParameters httpParams = new HttpParameters();
        httpParams.putAll(additionalParameters, true);
        consumer.setAdditionalParameters(httpParams);
      }

      if (this.listener != null) {
        this.listener.prepareRequest(request);
      }

      consumer.sign(request);

      if (this.listener != null) {
        this.listener.prepareSubmission(request);
      }

      response = sendRequest(request);
      int statusCode = response.getStatusCode();

      boolean requestHandled = false;
      if (this.listener != null) {
        requestHandled = this.listener.onResponseReceived(request, response);
      }
      if (requestHandled) {
        return;
      }

      if (statusCode >= 300) {
        handleUnexpectedResponse(statusCode, response);
      }

      HttpParameters responseParams = OAuth.decodeForm(response.getContent());

      String token = responseParams.getFirst(OAuth.OAUTH_TOKEN);
      String secret = responseParams.getFirst(OAuth.OAUTH_TOKEN_SECRET);
      responseParams.remove(OAuth.OAUTH_TOKEN);
      responseParams.remove(OAuth.OAUTH_TOKEN_SECRET);

      setResponseParameters(responseParams);

      if (token == null || secret == null) {
        throw new OAuthExpectationFailedException(
            "Request token or token secret not set in server reply. "
                + "The service provider you use is probably buggy.");
      }

      consumer.setTokenWithSecret(token, secret);

    } catch (OAuthNotAuthorizedException e) {
      throw e;
    } catch (OAuthExpectationFailedException e) {
      throw e;
    } catch (Exception e) {
      throw new OAuthCommunicationException(e);
    } finally {
      try {
        closeConnection(request, response);
      } catch (Exception e) {
        throw new OAuthCommunicationException(e);
      }
    }
  }