private int addCardSet(String title, String description) throws Exception { String urlTitle = URLEncoder.encode(title); String urlDescription = URLEncoder.encode(description); String url = FE_API_ADD_CARDSET + "&title=" + urlTitle + "&tags=" + urlTitle + "&description=" + urlDescription + "&private=false&oauth_token_secret=" + oauthTokenSecret + "&oauth_token=" + oauthToken; url = consumer.sign(url); String jsonString = DownloaderUtils.downloadJSONString(url); Log.v(TAG, "Request url: " + url); Log.v(TAG, jsonString); JSONObject rootObject = new JSONObject(jsonString); String status = rootObject.getString("response_type"); if (!status.equals("ok")) { throw new IOException("Status is not OK. Status: " + status); } JSONObject resultObject = rootObject.getJSONObject("results"); int cardSetId = resultObject.getInt("card_set_id"); return cardSetId; }
private void addCard(int cardSetId, String question, String answer) throws Exception { String url = FE_API_ADD_CARD + "&card_set_id=" + cardSetId + "&question=" + URLEncoder.encode(question) + "&answer=" + URLEncoder.encode(answer) + "&oauth_token_secret=" + oauthTokenSecret + "&oauth_token=" + oauthToken; Log.v(TAG, "Request url_old: " + url); url = consumer.sign(url); Log.v(TAG, "Request url_signed: " + url); String jsonString = DownloaderUtils.downloadJSONString(url); JSONObject rootObject = new JSONObject(jsonString); String status = rootObject.getString("response_type"); if (!status.equals("ok")) { Log.v(TAG, jsonString); throw new IOException("Adding card is not OK. Status: " + status); } }
private String[] getOAuthTokens() throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, ClientProtocolException, IOException { /* basically, if we're getting here and these things are set we should have already set this information. if not, well then kaboom!!! don't mess up sammy! */ if (oauth_callback != null && !oauth_callback.isEmpty()) { String[] result = new String[2]; result[0] = consumer.getToken(); result[1] = consumer.getTokenSecret(); return result; } ArrayList<BasicNameValuePair> xauth_params = new ArrayList<BasicNameValuePair>(); xauth_params.add(new BasicNameValuePair("x_auth_mode", "client_auth")); xauth_params.add(new BasicNameValuePair("x_auth_username", email)); xauth_params.add(new BasicNameValuePair("x_auth_password", password)); HttpPost post = new HttpPost("https://www.tumblr.com/oauth/access_token"); try { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(xauth_params); post.setEntity(entity); consumer.sign(post); HttpResponse response = client.execute(post); String s = convertToString(response.getEntity().getContent()); String[] tokens = s.split("&"); String[] result = new String[2]; result[0] = tokens[0].split("=")[1]; result[1] = tokens[1].split("=")[1]; return result; } catch (UnsupportedEncodingException e) { } return null; }
public HttpURLConnection getConnection(String url) throws IOException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException { try { URL u = new URL(url); HttpURLConnection uc = (HttpURLConnection) u.openConnection(); if (consumer != null) { try { log.info("Signing the oAuth consumer"); consumer.sign(uc); } catch (OAuthMessageSignerException e) { log.error("Error signing the consumer", e); throw e; } catch (OAuthExpectationFailedException e) { log.error("Error signing the consumer", e); throw e; } catch (OAuthCommunicationException e) { log.error("Error signing the consumer", e); throw e; } uc.connect(); } return uc; } catch (IOException e) { log.error("Error signing the consumer", e); throw e; } }
public String call(String url, Map<String, String> fields) { // create an HTTP request to a protected resource HttpGet request = new HttpGet(endpoint); HttpParams p = new BasicHttpParams(); for (Entry<String, String> en : fields.entrySet()) { p.setParameter(en.getKey(), en.getValue()); } request.setParams(p); // sign the request try { consumer2.sign(request); } catch (OAuthMessageSignerException e) { e.printStackTrace(); } catch (OAuthExpectationFailedException e) { e.printStackTrace(); } // send the request HttpClient httpClient = new DefaultHttpClient(); try { HttpResponse response = httpClient.execute(request); return convertStreamToString(response.getEntity().getContent()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
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; } }
public JSONArray getUserTimezoneHistory( UpdateInfo updateInfo, String api_key, OAuthConsumer consumer) throws Exception { long then = System.currentTimeMillis(); String requestUrl = "http://api.bodymedia.com/v2/json/timezone?api_key=" + api_key; HttpGet request = new HttpGet(requestUrl); consumer.sign(request); HttpClient client = env.getHttpClient(); enforceRateLimits(getRateDelay(updateInfo)); HttpResponse response = client.execute(request); final int statusCode = response.getStatusLine().getStatusCode(); final String reasonPhrase = response.getStatusLine().getReasonPhrase(); if (statusCode == 200) { countSuccessfulApiCall(updateInfo.apiKey, updateInfo.objectTypes, then, requestUrl); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String json = responseHandler.handleResponse(response); JSONObject userInfo = JSONObject.fromObject(json); return userInfo.getJSONArray("timezones"); } else { countFailedApiCall( updateInfo.apiKey, updateInfo.objectTypes, then, requestUrl, "", statusCode, reasonPhrase); throw new Exception( "Error: " + statusCode + " Unexpected error trying to bodymedia timezone for user " + updateInfo.apiKey.getGuestId()); } }
@Override protected String doInBackground(String... urls) { HttpClient httpClient = new DefaultHttpClient(); Log.d("inbgactivity", urls[0]); if (networkStatus() == NETWORK_STATUS_OK) { if (method.equalsIgnoreCase("POST")) { try { HttpPost request = new HttpPost(urls[0]); Log.d("asd", this.params); StringEntity parameters = new StringEntity(params); request.addHeader("content-type", "application/json"); request.setEntity(parameters); HttpResponse response = httpClient.execute(request); return EntityUtils.toString(response.getEntity()); } catch (Exception e) { e.printStackTrace(); Log.d("bg exception", e.toString()); return null; } } else if (method.equalsIgnoreCase("GET")) { try { HttpGet request = new HttpGet(urls[0]); HttpResponse response = httpClient.execute(request); return EntityUtils.toString(response.getEntity()); } catch (Exception e) { e.printStackTrace(); Log.d("bg exception", e.toString()); return null; } } else if (method.equalsIgnoreCase("OAUTH_GET")) { try { OAuthConsumer consumer = new DefaultOAuthConsumer(LINKEDIN_API_KEY, LINKEDIN_SECRET_KEY); consumer.setTokenWithSecret(urls[1], urls[2]); URL url = new URL(urls[0]); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.setRequestMethod("GET"); request.setUseCaches(true); consumer.sign(request); request.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); Log.d("as", sb.toString()); return sb.toString(); } catch (Exception e) { e.printStackTrace(); Log.d("bg exception", e.toString()); return null; } } else return null; } else { return null; } }
public static void test1() throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException, IOException { Properties prop = new Properties(); InputStream in = KivaApiExampleWithSignPost.class.getResourceAsStream("/signpost.properties"); prop.load(in); String consumerKey = prop.getProperty("oauth.consumer.key"); String consumerSecret = prop.getProperty("oauth.consumer.secret"); in.close(); System.setProperty("debug", "true"); OAuthConsumer consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret); // Note: we have to add the consumer key in the authorization URL to make it work OAuthProvider provider = new CommonsHttpOAuthProvider( REQUEST_TOKEN_URL, ACCESS_TOKEN_URL, AUTHORIZATION_URL + "&client_id=" + consumerKey); /* * This has to be done once to get request token */ provider.setOAuth10a(true); // for some reason, SignPost does not append oauth_callback so I // added it directly into the AUTHORIZATION_URL String requestUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL); System.out.println("Copy/Paste the following URL in your browser: " + requestUrl); System.out.print("Enter your token: "); // read authorization code Scanner scanner = new Scanner(System.in); String authorizationCode = scanner.nextLine().trim(); provider.retrieveAccessToken(consumer, authorizationCode); String accessToken = consumer.getToken(); String tokenSecret = consumer.getTokenSecret(); System.out.println("Token: " + accessToken + ". Secret: " + tokenSecret); // store token and secret somewhere in a database or in a file // so that it can be used later /* * To be done whenever you use the Kiva API */ OAuthConsumer newConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret); newConsumer.setTokenWithSecret(accessToken, tokenSecret); HttpGet request = new HttpGet(RESOURCE_URL); consumer.sign(request); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(request); // send request and get content String content = IOUtil.toString(response.getEntity().getContent()); System.out.println(content); }
public static boolean signWithSignpost(OAuthConsumer consumer, HttpPost request) { try { consumer.sign(request); return true; } catch (OAuthExpectationFailedException e) { } catch (OAuthCommunicationException e) { } catch (OAuthMessageSignerException e) { } return false; }
private JSONObject OAuthGet(String url) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, ClientProtocolException, IOException, IllegalStateException, JSONException { String[] oauth_tokens = getOAuthTokens(); consumer.setTokenWithSecret(oauth_tokens[0], oauth_tokens[1]); HttpGet req = new HttpGet(url); consumer.sign(req); HttpResponse response = client.execute(req); JSONObject result = new JSONObject(convertToString(response.getEntity().getContent())); return result; }
/** * Get signed request * * @param entity * @return the signed request * @throws UnsupportedEncodingException when program ask for a character converter unavailable * @throws OAuthMessageSignerException (signpost exception) OAuth Signing failed * @throws OAuthExpectationFailedException (signpost exception) Authorized request token or token * secret not set * @throws OAuthCommunicationException (signpost exception) Communication with the service * provider failed, response code: 403 */ private HttpPost getSignedRequest(String entity) throws UnsupportedEncodingException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException { // set entity and parameters of the request HttpPost request = new HttpPost(this.getServer()); request.setEntity(new StringEntity(entity)); request.setParams(mParameters); // load saved keys token and configure consumer with provider tokens loadSavedKeys(); // sign the request to authenticate mConsumer.sign(request); return request; }
/** * 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; }
void signWithSignpost( HttpUriRequest hcRequest, String consumerKey0, String consumerSecret0, String token, String tokenSecret) throws IndivoClientException { logger.info("in signWithSignpost"); String consumerKey = null; String consumerSecret = null; if (consumerKey0 == null) { consumerKey = defaultConsumerKey; consumerSecret = defaultConsumerSecret; } else { consumerKey = consumerKey0; consumerSecret = consumerSecret0; } logger.info( "in signWithSignpost pre new DefaultOAuthConsumer " + consumerKey + " " + consumerSecret); OAuthConsumer oauthConsumer = new DefaultOAuthConsumer(consumerKey, consumerSecret); logger.info("in signWithSignpost post new DefaultOAuthConsumer"); oauth.signpost.http.HttpRequest spRequest = new HttpRequestAdapter(hcRequest); logger.info("in signWithSignpost post new HttpRequestAdapter"); if (token == null) { oauthConsumer.setTokenWithSecret(null, ""); } else { oauthConsumer.setTokenWithSecret(token, tokenSecret); } try { String whatDebugWas = null; /* un-comment to get SBS */ // whatDebugWas = System.setProperty("debug", "true"); logger.info("in signWithSignpost pre sign"); oauthConsumer.sign(spRequest); logger.info("in signWithSignpost post sign"); /* un-comment this also when un-commenting the above */ // if (whatDebugWas == null) { System.clearProperty("debug"); } else { // System.setProperty("debug", whatDebugWas); } } catch (OAuthMessageSignerException omse) { throw new IndivoClientException(omse); } catch (OAuthExpectationFailedException oefe) { throw new IndivoClientException(oefe); } catch (oauth.signpost.exception.OAuthCommunicationException oce) { throw new IndivoClientException(oce); } }
/** Retrieve the OAuth Request Token and present a browser to the user to authorize the token. */ @Override protected Uri doInBackground(Uri... params) { determineProgressGoal(null); Uri trackUri = null; String trackName = mAdapter.getBreadcrumbsTracks().getValueForItem(mTrack, BreadcrumbsTracks.NAME); HttpEntity responseEntity = null; try { HttpUriRequest request = new HttpGet( "http://api.gobreadcrumbs.com/v1/tracks/" + mTrack.second + "/placemarks.gpx"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } mConsumer.sign(request); if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "Execute request: " + request.getURI()); for (Header header : request.getAllHeaders()) { Log.d(TAG, " with header: " + header.toString()); } } HttpResponse response = mHttpclient.execute(request); responseEntity = response.getEntity(); InputStream is = responseEntity.getContent(); InputStream stream = new BufferedInputStream(is, 8192); if (BreadcrumbsAdapter.DEBUG) { stream = XmlCreator.convertStreamToLoggedStream(TAG, stream); } trackUri = importTrack(stream, trackName); } catch (OAuthMessageSignerException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } catch (OAuthExpectationFailedException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } catch (OAuthCommunicationException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } catch (IOException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } } return trackUri; }
private static void sendRequest() throws Exception { HttpGet request = new HttpGet(url); // sign the request consumer.sign(request); // send the request HttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(request); InputStream inputStream = response.getEntity().getContent(); String result = convertStreamToString(inputStream); System.out.println(result); }
/** * Signs the connection with an OAuth authentication header * * @param connection the connection * @throws OsmTransferException thrown if there is currently no OAuth Access Token configured * @throws OsmTransferException thrown if signing fails */ protected void addOAuthAuthorizationHeader(HttpURLConnection connection) throws OsmTransferException { if (oauthParameters == null) { oauthParameters = OAuthParameters.createFromPreferences(Main.pref); } OAuthConsumer consumer = oauthParameters.buildConsumer(); OAuthAccessTokenHolder holder = OAuthAccessTokenHolder.getInstance(); if (!holder.containsAccessToken()) throw new MissingOAuthAccessTokenException(); consumer.setTokenWithSecret(holder.getAccessTokenKey(), holder.getAccessTokenSecret()); try { consumer.sign(connection); } catch (OAuthException e) { throw new OsmTransferException( tr("Failed to sign a HTTP connection with an OAuth Authentication header"), e); } }
public static void main(String[] args) throws Exception { OAuthConsumer consumer = new DefaultOAuthConsumer( "iIlNngv1KdV6XzNYkoLA", "exQ94pBpLXFcyttvLoxU2nrktThrlsj580zjYzmoM", SignatureMethod.HMAC_SHA1); OAuthProvider provider = new DefaultOAuthProvider( consumer, "http://twitter.com/oauth/request_token", "http://twitter.com/oauth/access_token", "http://twitter.com/oauth/authorize"); System.out.println("Fetching request token from Twitter..."); // we do not support callbacks, thus pass OOB String authUrl = provider.retrieveRequestToken(OAuth.OUT_OF_BAND); System.out.println("Request token: " + consumer.getToken()); System.out.println("Token secret: " + consumer.getTokenSecret()); System.out.println("Now visit:\n" + authUrl + "\n... and grant this app authorization"); System.out.println("Enter the PIN code and hit ENTER when you're done:"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String pin = br.readLine(); System.out.println("Fetching access token from Twitter..."); provider.retrieveAccessToken(pin); System.out.println("Access token: " + consumer.getToken()); System.out.println("Token secret: " + consumer.getTokenSecret()); URL url = new URL("http://twitter.com/statuses/mentions.xml"); HttpURLConnection request = (HttpURLConnection) url.openConnection(); consumer.sign(request); System.out.println("Sending request to Twitter..."); request.connect(); System.out.println( "Response: " + request.getResponseCode() + " " + request.getResponseMessage()); }
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; }
/** * Makes an API request to Neoseeker * * @param apiCall API Call (ex. members/me/) * @return JSON results * @throws Exception */ public String makeRequest(String apiCall) throws Exception { String result = ""; String baseAPIURL = "http://api.neoseeker.com/"; HttpGet request = new HttpGet(baseAPIURL + apiCall); consumer.sign(request); HttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(request); InputStream is = response.getEntity().getContent(); StringWriter writer = new StringWriter(); IOUtils.copy(is, writer); result = writer.toString(); return result; }
public static void main(String[] args) throws Exception { OAuthConsumer consumer = new DefaultOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET); OAuthProvider provider = new DefaultOAuthProvider( NETFLIX_REQUEST_TOKEN_URL, NETFLIX_ACCESS_TOKEN_URL, NETFLIX_AUTHORIZE_URL); System.out.println("Fetching request token from Netflix..."); // we do not support callbacks, thus pass OOB String authUrl = provider.retrieveRequestToken(consumer, OAuth.OUT_OF_BAND); authUrl = OAuth.addQueryParameters( authUrl, OAuth.OAUTH_CONSUMER_KEY, CONSUMER_KEY, "application_name", APPLICATION_NAME); System.out.println("Request token: " + consumer.getToken()); System.out.println("Token secret: " + consumer.getTokenSecret()); System.out.println("Now visit:\n" + authUrl + "\n... and grant this app authorization"); System.out.println("Enter the PIN code and hit ENTER when you're done:"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String pin = br.readLine(); System.out.println("Fetching access token from Twitter..."); provider.retrieveAccessToken(consumer, pin); System.out.println("Access token: " + consumer.getToken()); System.out.println("Token secret: " + consumer.getTokenSecret()); URL url = new URL("http://api.netflix.com/catalog/titles"); HttpURLConnection request = (HttpURLConnection) url.openConnection(); consumer.sign(request); System.out.println("Sending request..."); request.connect(); System.out.println( "Response: " + request.getResponseCode() + " " + request.getResponseMessage()); }
private static String getUpdatedWikiContents(UserPreferences prefs) throws IOException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException { final OAuthConsumer consumer = new DefaultOAuthConsumer( AppCredentials.INSTANCE.getKey(), AppCredentials.INSTANCE.getSecret()); consumer.setTokenWithSecret(prefs.getOauthTokenKey(), prefs.getOauthTokenSecret()); final URL url = new URL(DropboxWikiClient.FILE_BASE_URL + prefs.getWikiPath()); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("GET"); consumer.sign(connection); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { String contents = extractString(connection.getInputStream()); return contents; } LOG.error("Error getting wiki. Got response {}", connection.getResponseCode()); throw new IOException(); }
public String getUserRegistrationDate( UpdateInfo updateInfo, String api_key, OAuthConsumer consumer) throws Exception { // dev only: artificially make history shorter // return "20130810"; long then = System.currentTimeMillis(); String requestUrl = "http://api.bodymedia.com/v2/json/user/info?api_key=" + api_key; HttpGet request = new HttpGet(requestUrl); consumer.sign(request); HttpClient client = env.getHttpClient(); enforceRateLimits(getRateDelay(updateInfo)); HttpResponse response = client.execute(request); int statusCode = response.getStatusLine().getStatusCode(); final String reasonPhrase = response.getStatusLine().getReasonPhrase(); if (statusCode == 200) { countSuccessfulApiCall(updateInfo.apiKey, updateInfo.objectTypes, then, requestUrl); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String json = responseHandler.handleResponse(response); JSONObject userInfo = JSONObject.fromObject(json); return userInfo.getString("registrationDate"); } else { countFailedApiCall( updateInfo.apiKey, updateInfo.objectTypes, then, requestUrl, reasonPhrase, statusCode, reasonPhrase); throw new Exception( "Error: " + statusCode + " Unexpected error trying to get BodyMedia user registration date for guestId=" + updateInfo.getGuestId()); } }
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 HttpRequest sign(HttpURLConnection conn) throws Exception { return consumer.sign(conn); }
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String oauth_consumer_key = request.getParameter("oauth_consumer_key"); String oauth_nonce = request.getParameter("oauth_nonce"); String oauth_signature = request.getParameter("oauth_signature"); String oauth_signature_method = request.getParameter("oauth_signature_method"); String oauth_timestamp = request.getParameter("oauth_timestamp"); String oauth_version = request.getParameter("oauth_version"); String eventUrl = request.getParameter("eventUrl"); // signing the eventurl that was passed so we get authorization to use it. OAuthConsumer consumer = new DefaultOAuthConsumer("test6-40942", "oQ4q4oBiv9y4jPr7"); URL url = new URL(eventUrl); HttpURLConnection requestUrl = (HttpURLConnection) url.openConnection(); consumer.sign(requestUrl); requestUrl.connect(); // parsing the xml into a string String result = null; StringBuilder sb = new StringBuilder(); InputStream is = new BufferedInputStream(requestUrl.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String inputLine = ""; while ((inputLine = br.readLine()) != null) { sb.append(inputLine); } result = sb.toString(); // parsing certain elements of xml to display the current user information of buying a // specific product and getting the returnUrl to finish the transaction DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource src = new InputSource(); src.setCharacterStream(new StringReader(result)); Document doc = builder.parse(src); String creatorName = doc.getElementsByTagName("fullName").item(0).getTextContent(); String companyName = doc.getElementsByTagName("name").item(0).getTextContent(); String edition = doc.getElementsByTagName("editionCode").item(0).getTextContent(); String returnUrl = doc.getElementsByTagName("returnUrl").item(0).getTextContent(); System.out.print(creatorName); System.out.print(companyName); System.out.print(edition); System.out.print(returnUrl); response.sendRedirect( "displayinfo.jsp?fullName=" + creatorName + "&companyName=" + companyName + "&edition=" + edition + "&returnUrl=" + returnUrl); } catch (OAuthMessageSignerException ex) { Logger.getLogger(Buy.class.getName()).log(Level.SEVERE, null, ex); } catch (OAuthExpectationFailedException ex) { Logger.getLogger(Buy.class.getName()).log(Level.SEVERE, null, ex); } catch (OAuthCommunicationException ex) { Logger.getLogger(Buy.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(Buy.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(Buy.class.getName()).log(Level.SEVERE, null, ex); } }
/** Retrieve the OAuth Request Token and present a browser to the user to authorize the token. */ @Override protected Void doInBackground(Void... params) { HttpEntity responseEntity = null; mBundleIds = new HashSet<Integer>(); mBundles = new LinkedList<Object[]>(); try { HttpUriRequest request = new HttpGet("http://api.gobreadcrumbs.com/v1/bundles.xml"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } mConsumer.sign(request); if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "Execute request: " + request.getURI()); for (Header header : request.getAllHeaders()) { Log.d(TAG, " with header: " + header.toString()); } } HttpResponse response = mHttpclient.execute(request); responseEntity = response.getEntity(); InputStream is = responseEntity.getContent(); InputStream stream = new BufferedInputStream(is, 8192); if (BreadcrumbsAdapter.DEBUG) { stream = XmlCreator.convertStreamToLoggedStream(TAG, stream); } XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(stream, "UTF-8"); String tagName = null; int eventType = xpp.getEventType(); String bundleName = null, bundleDescription = null; Integer bundleId = null; while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { tagName = xpp.getName(); } else if (eventType == XmlPullParser.END_TAG) { if ("bundle".equals(xpp.getName()) && bundleId != null) { mBundles.add(new Object[] {bundleId, bundleName, bundleDescription}); } tagName = null; } else if (eventType == XmlPullParser.TEXT) { if ("description".equals(tagName)) { bundleDescription = xpp.getText(); } else if ("id".equals(tagName)) { bundleId = Integer.parseInt(xpp.getText()); mBundleIds.add(bundleId); } else if ("name".equals(tagName)) { bundleName = xpp.getText(); } } eventType = xpp.next(); } } catch (OAuthMessageSignerException e) { mAdapter.removeAuthentication(); handleError( mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "Failed to sign the request with authentication signature"); } catch (OAuthExpectationFailedException e) { mAdapter.removeAuthentication(); handleError( mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "The request did not authenticate"); } catch (OAuthCommunicationException e) { mAdapter.removeAuthentication(); handleError( mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "The authentication communication failed"); } catch (IOException e) { handleError( mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "A problem during communication"); } catch (XmlPullParserException e) { handleError( mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "A problem while reading the XML data"); } catch (IllegalStateException e) { handleError( mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "A problem during communication"); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.w(TAG, "Failed closing inputstream"); } } } return null; }