예제 #1
0
  public AuthTokenObject getAccessToken(String verifier) {
    try {
      this.provider.retrieveAccessToken(this.consumer, verifier);
    } catch (OAuthMessageSignerException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    } catch (OAuthNotAuthorizedException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    } catch (OAuthExpectationFailedException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    } catch (OAuthCommunicationException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }

    AuthTokenObject access = new AuthTokenObject();
    access.tokenKey = this.consumer.getToken();
    access.tokenSecret = this.consumer.getTokenSecret();

    return access;
  }
예제 #2
0
  @Override
  public HttpResponse executeAuthenticatedHttpRequest(HttpUriRequest request)
      throws ThoundsConnectionException {
    try {
      consumer.sign(request);
      HttpResponse response;
      synchronized (httpclient) {
        response = httpclient.execute(request);
      }
      return response;
    } catch (OAuthMessageSignerException 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();
    } catch (IOException e) {
      throw new ThoundsConnectionException();
    }

    return null;
  }
예제 #3
0
  public String getAuthorizationURL(String callbackURL) {

    String authUrl = null;
    try {
      authUrl = this.provider.retrieveRequestToken(this.consumer, callbackURL);
    } catch (OAuthMessageSignerException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    } catch (OAuthNotAuthorizedException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    } catch (OAuthExpectationFailedException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    } catch (OAuthCommunicationException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }
    this.requestKey = this.consumer.getToken();
    this.requestSecret = this.consumer.getTokenSecret();

    return authUrl;
  }
  public String makeServiceCall(String url) {

    OAuthConsumer oAuthConsumer = new CommonsHttpOAuthConsumer(consumerKeyStr, consumerSecretStr);
    oAuthConsumer.setTokenWithSecret(accessTokenStr, accessTokenSecretStr);
    HttpGet httpGet = new HttpGet(url);

    try {
      oAuthConsumer.sign(httpGet);
      HttpClient httpClient = new DefaultHttpClient();
      HttpResponse httpResponse = httpClient.execute(httpGet);

      HttpEntity httpEntity = httpResponse.getEntity();
      String jsonResponse = EntityUtils.toString(httpEntity);
      return jsonResponse;

    } catch (OAuthMessageSignerException e) {
      e.printStackTrace();
      return null;
    } catch (OAuthExpectationFailedException e) {
      e.printStackTrace();
      return null;
    } catch (OAuthCommunicationException e) {
      e.printStackTrace();
      return null;
    } catch (ClientProtocolException e) {
      e.printStackTrace();
      return null;
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
  }
  /**
   * Creates a connection to the Streaming Filter API
   *
   * @param baseUrl the URL for Twitter Filter API
   * @param outFilePath Location to place the exported file
   */
  private InputStream CreateStreamingConnection(String baseUrl) {
    HttpClient httpClient = new DefaultHttpClient();
    httpClient
        .getParams()
        .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(90000));
    // Step 1: Initialize OAuth Consumer
    OAuthConsumer consumer =
        new CommonsHttpOAuthConsumer(OAuthUtils.CONSUMER_KEY, OAuthUtils.CONSUMER_SECRET);
    consumer.setTokenWithSecret(OAuthToken.getAccessToken(), OAuthToken.getAccessSecret());
    // Step 2: Create a new HTTP POST request and set parameters
    HttpPost httppost = new HttpPost(baseUrl);
    try {
      httppost.setEntity(new UrlEncodedFormEntity(CreateRequestBody(), "UTF-8"));
    } catch (UnsupportedEncodingException ex) {
      ex.printStackTrace();
    }
    try {
      // Step 3: Sign the request
      consumer.sign(httppost);
    } catch (OAuthMessageSignerException ex) {
      ex.printStackTrace();
    } catch (OAuthExpectationFailedException ex) {
      ex.printStackTrace();
    } catch (OAuthCommunicationException ex) {
      ex.printStackTrace();
    }
    HttpResponse response;
    InputStream is = null;
    try {
      // Step 4: Connect to the API
      response = httpClient.execute(httppost);
      if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException("Got status " + response.getStatusLine().getStatusCode());
      } else {
        System.out.println(OAuthToken.getAccessToken() + ": Processing from " + baseUrl);
        HttpEntity entity = response.getEntity();
        try {
          is = entity.getContent();
        } catch (IOException ex) {
          ex.printStackTrace();
        } catch (IllegalStateException ex) {
          ex.printStackTrace();
        }
      }
    } catch (IOException ex) {
      ex.printStackTrace();
    }

    return is;
  }
예제 #6
0
  private HttpGet connect(Authentication app) {
    OAuthConsumer consumer =
        new CommonsHttpOAuthConsumer(app.getConsumerKey(), app.getConsumerSecret());
    consumer.setTokenWithSecret(app.getAccessToken(), app.getAccessSecret());
    HttpGet request = new HttpGet("https://stream.twitter.com/1.1/statuses/sample.json");

    try {
      consumer.sign(request);
    } catch (OAuthMessageSignerException e) {
      e.printStackTrace();
    } catch (OAuthExpectationFailedException e) {
      e.printStackTrace();
    } catch (OAuthCommunicationException e) {
      e.printStackTrace();
    }

    return request;
  }
예제 #7
0
  public HttpURLConnection sign(HttpURLConnection request) {
    try {
      this.consumer.sign(request);
    } catch (OAuthMessageSignerException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    } catch (OAuthExpectationFailedException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    } catch (OAuthCommunicationException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }

    return request;
  }
예제 #8
0
    @Override
    protected String doInBackground(String... params) {
      String message = null;
      String verifier = params[0];
      try {
        // Get the token
        Log.d(TAG, "mConsumer: " + mConsumer);
        Log.d(TAG, "mProvider: " + mProvider);
        mProvider.retrieveAccessToken(mConsumer, verifier);
        String token = mConsumer.getToken();
        String tokenSecret = mConsumer.getTokenSecret();
        mConsumer.setTokenWithSecret(token, tokenSecret);

        Log.d(
            TAG,
            String.format(
                "verifier: %s, token: %s, tokenSecret: %s", verifier, token, tokenSecret));

        // Store token in prefs
        prefs.edit().putString("token", token).putString("tokenSecret", tokenSecret).commit();

        // Make a Twitter object
        oauthClient = new OAuthSignpostClient(OAUTH_KEY, OAUTH_SECRET, token, tokenSecret);
        twitter = new Twitter("MarkoGargenta", oauthClient);

        Log.d(TAG, "token: " + token);
      } catch (OAuthMessageSignerException e) {
        message = "OAuthMessageSignerException";
        e.printStackTrace();
      } catch (OAuthNotAuthorizedException e) {
        message = "OAuthNotAuthorizedException";
        e.printStackTrace();
      } catch (OAuthExpectationFailedException e) {
        message = "OAuthExpectationFailedException";
        e.printStackTrace();
      } catch (OAuthCommunicationException e) {
        message = "OAuthCommunicationException";
        e.printStackTrace();
      }
      return message;
    }
예제 #9
0
 public HttpResponse signRequest(String token, String tokenSecret, HttpPost post) {
   httpOauthConsumer = new CommonsHttpOAuthConsumer(APP_KEY, APP_SECRET);
   httpOauthConsumer.setTokenWithSecret(token, tokenSecret);
   HttpResponse response = null;
   try {
     httpOauthConsumer.sign(post);
   } catch (OAuthMessageSignerException e) {
     e.printStackTrace();
   } catch (OAuthExpectationFailedException e) {
     e.printStackTrace();
   } catch (OAuthCommunicationException e) {
     e.printStackTrace();
   }
   try {
     response = new DefaultHttpClient().execute(post);
   } catch (ClientProtocolException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return response;
 }
예제 #10
0
 /**
  * 获得AccessToken
  *
  * @param intent
  * @return UserInfo
  */
 public User getAccessToken(Intent intent) {
   Uri uri = intent.getData();
   // 处理获取返回的oauth_verifier参数
   String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
   try {
     httpOauthprovider.setOAuth10a(true);
     httpOauthprovider.retrieveAccessToken(httpOauthConsumer, verifier);
   } catch (OAuthMessageSignerException ex) {
     ex.printStackTrace();
   } catch (OAuthNotAuthorizedException ex) {
     ex.printStackTrace();
   } catch (OAuthExpectationFailedException ex) {
     ex.printStackTrace();
   } catch (OAuthCommunicationException ex) {
     ex.printStackTrace();
   }
   SortedSet<String> user_id = httpOauthprovider.getResponseParameters().get("user_id");
   String userToken = httpOauthConsumer.getToken();
   String userSecret = httpOauthConsumer.getTokenSecret();
   User user = new User(user_id.first(), userToken, userSecret);
   return user;
 }
예제 #11
0
 @Override
 protected String doInBackground(Void... params) {
   String authUrl;
   String message = null;
   try {
     authUrl = mProvider.retrieveRequestToken(mConsumer, OAUTH_CALLBACK_URL);
     Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl));
     startActivity(intent);
   } catch (OAuthMessageSignerException e) {
     message = "OAuthMessageSignerException";
     e.printStackTrace();
   } catch (OAuthNotAuthorizedException e) {
     message = "OAuthNotAuthorizedException";
     e.printStackTrace();
   } catch (OAuthExpectationFailedException e) {
     message = "OAuthExpectationFailedException";
     e.printStackTrace();
   } catch (OAuthCommunicationException e) {
     message = "OAuthCommunicationException";
     e.printStackTrace();
   }
   return message;
 }
  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();
    }
  }
  private void dealing(List<NameValuePair> nvps) {
    String url = "http://api.t.sina.com.cn/blocks/exists.json";
    // 新建一个POST
    HttpPost post = new HttpPost(url);

    // 将参数加到post中
    try {
      post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    // 关闭Expect:100-Continue握手
    // 100-Continue握手需谨慎使用,因为遇到不支持HTTP/1.1协议的服务器或者代理时会引起问题
    post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
    // 生成CommonsHttpOAuthConsumer对象
    CommonsHttpOAuthConsumer choc =
        new CommonsHttpOAuthConsumer(Constant.consumerKey, Constant.consumerSecret);
    choc.setTokenWithSecret(Constant.userKey, Constant.userSecret);
    // 对post进行签名
    try {
      choc.sign(post);
    } catch (OAuthMessageSignerException 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();
    }
    // 发送post用来获得HttpResponse
    HttpClient hc = new DefaultHttpClient();
    HttpResponse rp = null;
    try {
      rp = hc.execute(post);
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    if (200 == rp.getStatusLine().getStatusCode()) {
      try {
        Log.v("getStatusLine", "OK");
        // 将HttpResponse中的内容读到buffer中
        InputStream is = rp.getEntity().getContent();
        Reader reader = new BufferedReader(new InputStreamReader(is), 4000);
        StringBuilder buffer = new StringBuilder((int) rp.getEntity().getContentLength());
        try {
          char[] tmp = new char[1024];
          int l;
          while ((l = reader.read(tmp)) != -1) {
            buffer.append(tmp, 0, l);
          }
        } finally {
          reader.close();
        }
        // 将buffer转为json可以支持的String类型
        String string = buffer.toString();
        // 销毁rp
        rp.getEntity().consumeContent();
        // 新建JSONObject来处理其中的数据
        try {
          JSONObject data = new JSONObject(string);
          Log.v("result", data.getString("result"));
          // result结果为true则该用户已被加黑名单,false则该用户未被加黑名单

        } catch (JSONException e) {
          e.printStackTrace();
        }

      } catch (IllegalStateException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }