Ok, I give up. Anyone have experience using Google's IssueAuthToken and MergeSession to authenticate with certain Google services that do not have official API access? In this case I'm trying to get Google bookmarks (from google.com/bookmarks).
I get the SID and LSID using getAuthToken and that works fine. I then call
Uri ISSUE_AUTH_TOKEN_URL = Uri.parse("https://accounts.google.com/IssueAuthToken?service=bookmarks&Session=false");
String url = ISSUE_AUTH_TOKEN_URL.buildUpon()
.appendQueryParameter("SID", sid)
.appendQueryParameter("LSID", lsid)
.build().toString();
I receive the "ubertoken".
I then do a GET to MergeSession and that's where it all goes wrong:
String url2 = "https://accounts.google.com/MergeSession?source=chrome&uberauth="+uberToken+"&service=bookmarks&continue=https%3A%2F%2Fwww.google.com%2Fbookmarks%2F";
HttpGet getCookies = new HttpGet(url2);
Looking through the headers of getCookies I am not seeing the extra cookies I should see, and I also see things like X-Frame-Options: DENY.
Help (please)!
Okay friends, here we go. It seems the above is now unreliable/broken at least occasionally as of August 2013. This is how I'm doing it now and it seems to work. It tries the above first, and if it fails, goes on to method #2.
final Account acct = am.getAccountsByType("com.google")[acctid];
final String tokenType = "weblogin:service=bookmarks&continue=https://www.google.com/bookmarks/";
am.getAuthToken(acct, tokenType, null, this, new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> future) {
try {
final String accessToken = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
if (accessToken.contains("WILL_NOT_SIGN_IN")) {
am.getAuthToken(acct, "SID", null, MainActivity.this, new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> future) {
try {
sid = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
} catch (OperationCanceledException e) {
finish();
} catch (Exception e) {
e.printStackTrace();
}
am.getAuthToken(acct, "LSID", null, MainActivity.this, new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> future) {
try {
lsid = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
} catch (OperationCanceledException e) {
finish();
} catch (Exception e) {
e.printStackTrace();
}
Thread t = new Thread() {
public void run() {
try {
Uri ISSUE_AUTH_TOKEN_URL = Uri.parse("https://www.google.com/accounts/IssueAuthToken?service=gaia&Session=false");
Uri TOKEN_AUTH_URL = Uri.parse("https://www.google.com/accounts/TokenAuth");
final HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
httpclient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
String url = ISSUE_AUTH_TOKEN_URL.buildUpon().appendQueryParameter("SID", sid).appendQueryParameter("LSID", lsid).build().toString();
HttpPost getUberToken = new HttpPost(url);
HttpResponse response = httpclient.execute(getUberToken);
String uberToken = EntityUtils.toString(response.getEntity(), "UTF-8");
final String accessToken2 = TOKEN_AUTH_URL.buildUpon()
.appendQueryParameter("source", "android-browser")
.appendQueryParameter("auth", uberToken)
.appendQueryParameter("continue", "https://www.google.com/bookmarks/").build().toString();
//do stuff
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
}, null);
}
}, null);
} else {
//do stuff
}
} catch (OperationCanceledException e) {
finish();
} catch (Exception e) {
finish();
}
}
}, null);
Related
I am struggling with something that really p*sses me off for several hours.
My android app manages to connect to a websoket, and receives json data which for now has worked perfectly, and here is the code for this:
runOnUiThread(new Runnable() {
#Override
public void run() {
mSocket.on("dev0", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
JSONObject incomingPositionFromSensor = new JSONObject( (String) args[0]);
double the_position = incomingPositionFromSensor.getDouble("position");
CalculateValue(the_position);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
This code above as I said works perfectly, and i get the data in everytime. HOWEVER, HOWEVER, HOWEVER: If i try to receive 2 json-objects at the sametime through this emittener, it does not work!!!!
Here is example when i try to receive multiple JSON objects, and NONE of them works!
runOnUiThread(new Runnable() {
#Override
public void run() {
mSocket.on("dev0", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
JSONObject incomingTargetFromSensor = new JSONObject( (String) args[0]);
int targetNum = incomingTargetFromSensor.getInt("target_number_count");
showTargetRep(targetNum); //NOT WORKING!
JSONObject incomingPositionFromSensor = new JSONObject( (String) args[0]);
double the_position = incomingPositionFromSensor.getDouble("position");
CalculateValue(the_position); //NOT WORKING!
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
In the first example I could receive the position data, and the code is exactly similar as the example above, but for some reasons it can not recevice data when i try to receive another JSON object.
Another example of why I always disliked JSON object.
Any help plz?
The solution at the end was to add multiple try/catches like this:
runOnUiThread(new Runnable() {
#Override
public void run() {
mSocket.on("dev0", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
JSONObject incomingTargetRepFromSensor = new JSONObject((String ) args[0]);
int target_rep = incomingTargetRepFromSensor.getInt("target_repetition_count");
showTargetRep(target_rep);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingDataFromSensor = new JSONObject((String ) args[0]);
double the_position = incomingDataFromSensor.getDouble("position");
CalculateValue(the_position);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingTargetSetFromSensor = new JSONObject((String ) args[0]);
int target_set = incomingTargetSetFromSensor.getInt("target_set_count");
showTargetSet(target_set);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingRepsFromSensor = new JSONObject((String ) args[0]);
int the_repetitions = incomingRepsFromSensor.getInt("repetitions");
showCurrentReps(the_repetitions);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingSetsFromSensor = new JSONObject((String ) args[0]);
int the_sets = incomingSetsFromSensor.getInt("sets");
showCurrentSets(the_sets);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
I integrated stripe in my android project. Now, I am generating token with card in stripe. That is working fine. But, I want to generate token with Bank Account. I searched in StackOverflow referred some of links. But, it doesn't worked for me. Is there is any way to generate stripe token with bank account in android?
The following code I used. But, it not worked.
Stripe.apiKey = "sk_test_...";
Map<String, Object> tokenParams = new HashMap<String, Object>();
Map<String, Object> bank_accountParams = new HashMap<String, Object>();
bank_accountParams.put("country", "US");
bank_accountParams.put("currency", "usd");
bank_accountParams.put("account_holder_name", "Jane Austen");
bank_accountParams.put("account_holder_type", "individual");
bank_accountParams.put("routing_number", "11000000");
bank_accountParams.put("account_number", "000123456789");
tokenParams.put("bank_account", bank_accountParams);
try {
Token s = Token.create(tokenParams);
Log.d("Token",s.getId());
tokens = s.getId();
} catch (AuthenticationException e) {
showAlertMessage("",e.getMessage());
} catch (CardException e) {
showAlertMessage("",e.getMessage());
} catch (APIException e) {
showAlertMessage("",e.getMessage());
} catch (InvalidRequestException e) {
showAlertMessage("", e.getMessage());
} catch (APIConnectionException e) {
showAlertMessage("",e.getMessage());
}
According to the new docs you need to add following line to gradle build:
compile 'com.stripe:stripe-android:4.0.1'
check for the latest version at this link
Then use the following code snippet:
Stripe stripe = new Stripe(this);
stripe.setDefaultPublishableKey("your_publishable_key");
BankAccount bankAccount = new BankAccount("accountNumber","countryCode","currency","routingNumber");
stripe.createBankAccountToken(bankAccount, new TokenCallback() {
#Override
public void onError(Exception error) {
Log.e("Stripe Error",error.getMessage());
}
#Override
public void onSuccess(com.stripe.android.model.Token token) {
Log.e("Bank Token", token.getId());
}
});
This should work like charm.
I made a mistake in my code. That is Token.create(tokenParams); should be handled with in AysncTask. Because it deals with network. After gone through their git repository I came to know. So, I handled that create token part in async task. The code I have changed is below:
int SDK_INT = android.os.Build.VERSION.SDK_INT;
final String[] tokens = {"new"};
Stripe.apiKey = "sk_test_0wgmvQOVjIpspIgKsoW7wtTp";
final Map<String, Object> tokenParams = new HashMap<String, Object>();
Map<String, Object> bank_accountParams = new HashMap<String, Object>();
bank_accountParams.put("country", "US");
bank_accountParams.put("currency", "usd");
bank_accountParams.put("account_holder_name", "Jayden Moore");
bank_accountParams.put("account_holder_type", "individual");
bank_accountParams.put("routing_number", "110000000");
bank_accountParams.put("account_number", "000123456789");
tokenParams.put("bank_account", bank_accountParams);
final Token[] responseToken = {null};
if (SDK_INT > 8)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
//your codes here
com.stripe.Stripe.apiKey = "sk_test_0wgmvQOVjIpspIgKsoW7wtTp";
new AsyncTask<Void, Void, Token>() {
String errorMsg = null;
#Override
protected Token doInBackground(Void... params) {
try {
return Token.create(tokenParams);
} catch (AuthenticationException e) {
e.printStackTrace();
return null;
} catch (InvalidRequestException e) {
e.printStackTrace();
return null;
} catch (APIConnectionException e) {
e.printStackTrace();
return null;
} catch (CardException e) {
e.printStackTrace();
return null;
} catch (APIException e) {
e.printStackTrace();
return null;
}
}
protected void onPostExecute(Token result) {
if (errorMsg == null) {
// success
} else {
// handleError(errorMsg);
}
}
}.execute();
}
I had the same problem and I fixed it by changing this line
compile 'com.stripe:stripe-android:+
into this line
compile 'com.stripe:stripe-android:1.1.1'
in my app.gradle file.
This might change for future releases.
This is my Asyntask code which is not firing the onPostExecute() Any one has any idea why this might be happening???
EDIT: The Asyntask is called this way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
.
.
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), SignUp.class);
startActivity(intent);
}
});
textView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Feedback.class);
startActivity(intent);
}
});
fbLoginButton = (LoginButton) findViewById(R.id.login_button);
fbLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
token=loginResult.getAccessToken().getToken().toString();
Log.v("tag", "Token:\n" + token);
try {
get_profile();
}catch (Exception ex) {
String error = ex.getMessage();
}
}
#Override
public void onCancel() {
Toast.makeText(MainActivity.this, "Login cancelled by user!", Toast.LENGTH_LONG).show();
System.out.println("Facebook Login failed!!");
}
#Override
public void onError(FacebookException e) {
Toast.makeText(MainActivity.this, "Login unsuccessful!", Toast.LENGTH_LONG).show();
System.out.println("Facebook Login failed!!");
}
});
}
The get_profile(); method is defined like this
//Method to get profile details
public void get_profile() throws UnsupportedEncodingException {
try {
// Calling async task to get json
new FetchOperation().execute();
} catch (Exception e) {
e.printStackTrace();
}
}
This is inside the Main class too
//Asynctask to get Getting fb profile details
private class FetchOperation extends AsyncTask<Void, Void, String> {
String fb_token;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Get user defined values
fb_token = token;
}
#Override
protected String doInBackground(Void... params) {
String response = "";
String Urls = "https://graph.facebook.com/me?access_token=";
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(Urls +token);
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
try {
httpResponse = httpclient.execute(httpget);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.v("Response", "Hi From e1 : " + e.toString());
} catch (IOException e) {
e.printStackTrace();
}
try {
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
Log.v("Response", "Hi From 2 : "+response.toString());
return response;
} catch (IOException e) {
e.printStackTrace();
Log.v("Response", "Hi From e2 : " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(String jsonStr) {
super.onPostExecute(jsonStr);
Log.v("tag", "Result:" + jsonStr);
if (jsonStr != null) {
try{
JSONObject jsonObj = new JSONObject(jsonStr);
String email = jsonObj.getString("email");
String firstName = jsonObj.getString("first_name");
String lastName = jsonObj.getString("last_name");
String gender = jsonObj.getString("gender");
String country = jsonObj.getString("locale");
id = jsonObj.getString("id");
user = firstName.concat(" ");
user = user.concat(lastName);
image = "http://graph.facebook.com/" + id + "/picture?type=large";
Log.v("Fb name", "Bla bla Name : " + user);
new UploadOperation().execute();
}
catch (JSONException e) {
e.printStackTrace();
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
}
This is the last lines of the logcat
06-29 14:30:49.927 2091-2091/com.example.kmi_dev.fbloginsample V/tag﹕ Token:
CA****************************************************************xr
06-29 14:30:50.697 2091-2135/com.example.kmi_dev.fbloginsample V/Response﹕ Hi From 2 : {"id":"910***********6","first_name":"Shivanshu","gender":"male","last_name":"Verma","link":"https:\/\/www.facebook.com\/app_scoped_user_id\/910***********6\/","locale":"en_GB","name":"Shivanshu Verma","timezone":5.5,"updated_time":"2015-06-22T04:17:39+0000","verified":true}
06-29 14:31:23.827 2091-2098/com.example.kmi_dev.fbloginsample W/art﹕ Suspending all threads took: 10ms
I intend to fire another asyntask which will then save the data fetched by this asyntask into the database.
Make these changes, it will work -
private class FetchOperation extends AsyncTask<Void, Void, String>
change to - private class FetchOperation extends AsyncTask<Void, String, String> , because, you are trying to return String.
response = EntityUtils.toString(httpEntity);
change to - response = EntityUtils.toString(httpEntity).toString();
at the next line of this you have actually done it.
At the very end of doInBackground method where return null;
change to - return response;
4.No need to call super in onPostExecute()
5.Inside onPostExecute() check jsonStr is null or not and do whatever you want to do if null and if contains json data.
Your JSONObject does not contain a JSONString "email", so it is falling over at line
String email = jsonObj.getString("email");
and going straight to catch block.
i am building an application in which i prompt users to register. I have a django-restful server running at back end , and i m trying to make HTTP post requests to my server on android client with DefaultHttpClient class. I get email, username etc from user and at the button's onClick event, i create an AsnycTask to execute the request. Here is the code for the activity:
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String userName = usernameEditText.getText().toString();
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
if( userName != null && email != null && password != null) {
new RegisterEventHandler().execute(userName , email , password);
}
}
});
....
class RegisterEventHandler extends AsyncTask<String, Integer, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
RequestHandler handler = new RequestHandler();
return handler.register(params[0], params[1], params[2]);
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if( result ) {
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setTitle(R.string.RegisterSuccessfullTitle);
builder.setMessage(R.string.RegisterSuccessfullMessage);
builder.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent redirect = new Intent(getApplicationContext() , SmartMapMainActivity.class);
startActivity(redirect);
}
});
builder.create().show();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setTitle(R.string.RegisterFailedTitle);
builder.setMessage(R.string.RegisterFailedMessage);
builder.create().show();
}
}
}
The RequestHandler class :
public class RequestHandler {
public boolean register(String userName , String email , String password) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://127.0.0.1/users/");
try {
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", userName);
jsonObj.put("email", email);
jsonObj.put("password", password);
StringEntity entity = new StringEntity(jsonObj.toString());
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == 200)
return true;
else
return false;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
}
The problem is, DefaultHttpClient's connManager(ClientConnectionManager) is always null and on the execute() method of the HttpClient, it always throws an IOException. I tried initializing the DefaultHttpClient in my activity , rather than in the AsyncTask's doInBackground method , but the result was the same.
Currently i need to make an application that can list all of Google Drive file.
i already did the account choosing and oauth process, an already get the token. but when i try to use API call to list all my file on Google Drive (By using drive.files.list) i didn't get any result, the arraylist of files which is supposed to hold all the file is still empty. i also got error :
java.net.unknownHostException www.googleapis.com cannot be resolved
this is my code :
SharedPreferences settings = getSharedPreferences(PREF, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("accountName", got.name);
editor.commit();
account=got;
amf=accMgr.getAuthToken(account, authTokenType, true,
new AccountManagerCallback<Bundle>(){
public void run(AccountManagerFuture<Bundle> arg0) {
try {
Bundle result;
Intent i;
String token;
Drive a;
result = arg0.getResult();
if (result.containsKey(accMgr.KEY_INTENT)) {
i = (Intent)result.get(accMgr.KEY_INTENT);
if (i.toString().contains("GrantCredentialsPermissionActivity")) {
// Will have to wait for the user to accept
// the request therefore this will have to
// run in a foreground application
cbt.startActivity(i);
} else {
cbt.startActivity(i);
}
}
else if (result.containsKey(accMgr.KEY_AUTHTOKEN)) {
accessProtectedResource.setAccessToken(result
.getString(accMgr.KEY_AUTHTOKEN));
buildService(result
.getString(accMgr.KEY_AUTHTOKEN),API_KEY);
/*else {
token = (String)result.get(AccountManager.KEY_AUTHTOKEN);*/
/*
* work with token
*/
// Remember to invalidate the token if the web service rejects it
// if(response.isTokenInvalid()){
// accMgr.invalidateAuthToken(authTokenType, token);
// }
}
} catch (OperationCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthenticatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, handler);
}
private void buildService(final String authToken, final String ApiKey) {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null);
b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
#Override
public void initialize(JsonHttpRequest request) throws IOException {
DriveRequest driveRequest = (DriveRequest) request;
driveRequest.setPrettyPrint(true);
driveRequest.setKey(ApiKey);
driveRequest.setOauthToken(authToken);
}
});
System.out.println(authToken);
service= b.build();
List<File> a=new ArrayList<File>();
try {
a = retrieveDriveFile(service);
System.out.println(a.size());
File c=a.get(0);
TextView ad=(TextView) findViewById(R.id.test);
ad.setText(c.getOriginalFilename());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public List<File> retrieveDriveFile(Drive service) throws IOException{
List<File> result = new ArrayList<File>();
Files.List request = service.files().list();
do {
try {
FileList files = request.execute();
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
} catch (IOException e) {
System.out.println("An error ssoccurred: " + e);
request.setPageToken(null);
}
} while (request.getPageToken() != null &&
request.getPageToken().length() > 0);
return result;
}
This would typically happen if you don't have a working internet connection on your device.
Also don't forget to add the following permission:
<uses-permission android:name="android.permission.INTERNET" />
This could happen also if you are behind a proxy. If that's the case please have a look at this question.
If you want to get all the file from Goolge Drive. Assume that you have already done the Account Choosing process and creating Drive (Drive mService) etc.
Now Under Button Click Event call this function
ButtonClickEvent
{
GetDriveData();
}
// FUNCTION TO RETRIEVE GOOGLE DRIVE DATA
private void GetDriveData()
{
private List<File> mResultList;
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
mResultList = new ArrayList<File>();
com.google.api.services.drive.Drive.Files f1 = mService.files();
com.google.api.services.drive.Drive.Files.List request = null;
do
{
try
{
request = f1.list();
request.setQ("trashed=false");
com.google.api.services.drive.model.FileList fileList = request.execute();
mResultList.addAll(fileList.getItems());
}
catch (UserRecoverableAuthIOException e)
{
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
}
catch (IOException e)
{
e.printStackTrace();
if (request != null)
{
request.setPageToken(null);
}
}
} while (request.getPageToken() !=null && request.getPageToken().length() > 0);
populateListView();//Calling to Populate Data to the List
}
});
t.start();
}
//Populating Retrieved data to List
private void populateListView()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
mFileArray = new String[mResultList.size()];
int i = 0;
for(File tmp : mResultList)
{
//System.out.println("FILE DATA "+tmp.getId()+"."+tmp.getFileSize()+".."+tmp.getFileExtension()+",,"+tmp.getMimeType()+"/"+tmp.getTitle());
mFileArray[i] = tmp.getTitle();
i++;
}
mAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, mFileArray);
mListView.setAdapter(mAdapter);
button2.setText("yes");
}
});
}