Creating an authentication manager with Android - android

Task
Create a one-time login feature using Android's authentication manager.
Current Process
I am currently using the Volley to read email and password from a form and send a request to a server
Required Change
To be able to create a one-time login for the use with credentials, using Android authentication manager following this post.
Question
1. My question lies in the implementation of the fetchTokenFromCredentials method under the getAuthToken of the authenticator class.
Here is the Java code snippet:
#Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options)
throws NetworkErrorException {
// We can add rejection of a request for a token type we
// don't support here
// Get the instance of the AccountManager that's making the
// request
final AccountManager am = AccountManager.get(mContext);
// See if there is already an authentication token stored
String authToken = am.peekAuthToken(account, authTokenType);
// If we have no token, use the account credentials to fetch
// a new one, effectively another logon
if (TextUtils.isEmpty(authToken)) {
final String password = am.getPassword(account);
if (password != null) {
authToken = fetchTokenFromCredentials(account.name, password, authTokenType)
}
}
// If we either got a cached token, or fetched a new one, hand
// it back to the client that called us.
if (!TextUtils.isEmpty(authToken)) {
final Bundle result = new Bundle();
result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
return result;
}
// If we get here, then we don't have a token, and we don't have
// a password that will let us get a new one (or we weren't able
// to use the password we do have). We need to fetch
// information from the user, we do that by creating an Intent
// to an Activity child class.
final Intent intent = new Intent(mContext, LoginActivity.class);
// We want to give the Activity the information we want it to
// return to the AccountManager. We'll cover that with the
// KEY_ACCOUNT_AUTHENTICATOR_RESPONSE parameter.
intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
// We'll also give it the parameters we've already looked up, or
// were given.
intent.putExtra(LoginActivity.ARG_IS_ADDING_NEW_ACCOUNT, false);
intent.putExtra(LoginActivity.ARG_ACCOUNT_NAME, account.name);
intent.putExtra(LoginActivity.ARG_ACCOUNT_TYPE, account.type);
intent.putExtra(LoginActivity.ARG_AUTH_TYPE, authTokenType);
// Remember that we have to return a Bundle, not an Intent, but
// we can tell the caller to run our intent to get its
// information with the KEY_INTENT parameter in the returned
// Bundle
final Bundle bundle = new Bundle();
bundle.putParcelable(AccountManager.KEY_INTENT, intent);
return bundle;
}
Previously I was using Volley , so my implementation of fetchTokenfromCredentials was something like shown below. However, I cannot use the same implementation now because I need to 'return' an authentication string. Volley does the login asynchronously so even if i add a return type to the function below it will always return null. Question: How do i wrap around THIS situation. What alternatives can I use?
public void fetchTokenfromCredentials(String name, String password) {
JSONObject loginObject = new JSONObject();
try {
loginObject.put("email", email);
loginObject.put("password", password);
} catch(JSONException e) {
e.printStackTrace();
}
// assume predefined url and params
JsonObjectRequest loginRequest = new HeaderRequest(Request.Method.POST, url + params, loginObject, new Response.Listener < JSONObject > () {#Override
public void onResponse(JSONObject response) {
try {
JSONObject headers = response.getJSONObject("headers");
// A simple use class that stores the id, username etc.
user = new User(response.getInt("id"), response.getString("name"), response.getString("authentication_token"), response.getString("email"));
// Previous code started a new main activity intent here
} catch(JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Failed response");
}
});
RequestQueueSingleton.getInstance(this.getApplicationContext()).addToRequestQueue(loginRequest);
}

You can make a synchronous, blocking request with Volley. That request will perform the network request, while blocking the thread and allow you to set a return type.
I am not fluent with Volley (Retrofit, FTW!) but I am pretty sure it's doable.
Take a look at this answer for a Synchronous request - https://stackoverflow.com/a/23808857

This is how I wrote the fetchTokensFromCredentials(email,password) function using the android Http Client Library:
URL was created using a uri builder
Uri builtUri = Uri.parse(AccountGeneral.LOGIN_QUERY).buildUpon()
.build();
URL url = null;
try {
url = new URL(builtUri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
// Stores result of the post response
String result = null;
// Create a JSON object for the email and password
JSONObject loginObject = new JSONObject();
try{
loginObject.put("email", email);
loginObject.put("password", password);
} catch(JSONException e) {
e.printStackTrace();
}
// Convert JSON to String
String data = loginObject.toString();
// Connection parameters
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
try {
//Start POST request - Write
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(data);
writer.close();
outputStream.close();
//Read response
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
result = sb.toString();
return result;
} finally {
urlConnection.disconnect();
}

Related

I have to Send a Json Object from Android App to Azure Rest API , Look into my Code help me ,works other API's

I want to send the json object
{
"PersonID" : "124",
"DeviceID": "123",
"ExpID": "1234",
"ID" : "4566"
}
to particular Azure Rest API URL
Ive Tried With the Code Given below it Works for URL-http://hmkcode.appspot.com/jsonservlet but not for my AZURE REST API's URL
MainActivity.java
private String httpPost(String myUrl) throws IOException, JSONException
{
String result = "";
URL url = new URL(myUrl);
// 1. create HttpURLConnection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
// 2. build JSON object
JSONObject jsonObject = buidJsonObject();
// 3. add JSON content to POST request body
setPostRequestContent(conn, jsonObject);
// 4. make POST request to the given URL
conn.connect();
// 5. return response message
return conn.getResponseMessage()+"";
}
private class HTTPAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
try {
return httpPost(urls[0]);
} catch (JSONException e) {
e.printStackTrace();
return "Error!";
}
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
//tvResult.setText(result);
}
}
public void send(View view) {
Toast.makeText(this, "Clicked", Toast.LENGTH_SHORT).show();
// perform HTTP POST request
new HTTPAsyncTask().execute("URL");
}
private JSONObject buidJsonObject() throws JSONException {
String w= "test";
String a= "ABCD";
JSONObject jsonObject = new JSONObject();
jsonObject.put("PersonID",token);
jsonObject.put("DeviceID", Settings.Secure.ANDROID_ID);
jsonObject.put("ExpID", w);
jsonObject.put("ID", a);
return jsonObject;
}
private void setPostRequestContent(HttpURLConnection conn, JSONObject jsonObject) throws IOException {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(jsonObject.toString());
Log.i(MainActivity.class.toString(), jsonObject.toString());
writer.flush();
writer.close();
os.close();
}
Activity_Main.xml
<Button
android:id="#+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:onClick="send"
android:text="Send"
tools:layout_editor_absoluteX="148dp"
tools:layout_editor_absoluteY="266dp" />
i want Token id , android id to be sent to Azure REST API.
Would like to help you out but I need a little more information from you. For instance, is your code snippet throwing any errors? What does conn.getRepsonseMessage() return? Also, you're indicating you're doing a post to that URL. Clicking on the link I do get JSON back but got a 500 error when I attempted to do a POST which leads me to believe that endpoint only accepts GETs.
The steps I would follow is use a tool like fiddler to make a POST to your Azure API endpoint and ensure there's no errors on that side if you're getting 200s back.

Integrate Paytm PGSDK_V2.0 Android

I am Integrating Paytm PGSDK_V2.0 in my android app. I have read all documentation on Github. I have understand everything.but the problem is in its earlier SDK where we can simply generate checksum using Paytm Merchant object Like:
PaytmMerchant merchant=new PaytmMerchant("Checksum generation url","Checksum verification url");
and put this in Service Like this
Service.initialize(Order,merchant,null);
But in new SDK it change to
Service.initialize(Order,null);
So please help me how to generate checksum in new SDK
Paytm has change process to increase the security. now in PGSDK_V2.0 first you have to generate through calling the api Checksum Generation on your server side
Like this:
#Override
protected String doInBackground(String... params) {
url ="http://xxx.co.in/generateChecksum.php";
JSONParser jsonParser = new JSONParser(MainActivity.this);
param="ORDER_ID=" + orderId+
"&MID="+YourMID+
"&CUST_ID="+custId+
"&CHANNEL_ID=WAP&INDUSTRY_TYPE_ID=Retail110&WEBSITE=xxxwap&TXN_AMOUNT="+billAmt+"&CALLBACK_URL=http://xxx.co.in/verifyChecksum.php";
JSONObject jsonObject = jsonParser.makeHttpRequest(url,"POST",param);
Log.e("CheckSum result >>",jsonObject.toString());
if(jsonObject != null){
Log.d("CheckSum result >>",jsonObject.toString());
try {
CHECKSUMHASH=jsonObject.has("CHECKSUMHASH")?jsonObject.getString("CHECKSUMHASH"):"";
Log.e("CheckSum result >>",CHECKSUMHASH);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
now after getting CHECKSUM string in your onPostExecute initialize paytm Service object and do further process Like This:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.hide();
Service = PaytmPGService.getProductionService();
/*PaytmMerchant constructor takes two parameters
1) Checksum generation url
2) Checksum verification url
Merchant should replace the below values with his values*/
//below parameter map is required to construct PaytmOrder object, Merchant should replace below map values with his own values
Map<String, String> paramMap = new HashMap<String, String>();
//these are mandatory parameters
paramMap.put("ORDER_ID", orderId);
//MID provided by paytm
paramMap.put("MID", yourMID);
paramMap.put("CUST_ID", custId);
paramMap.put("CHANNEL_ID", "WAP");
paramMap.put("INDUSTRY_TYPE_ID", "Retail");
paramMap.put("WEBSITE", "xxxwap");
paramMap.put("TXN_AMOUNT",billAmt);
//
paramMap.put("CALLBACK_URL" ,"http://xxx.co.in/verifyChecksum.php");
paramMap.put("CHECKSUMHASH" ,CHECKSUMHASH);
PaytmOrder Order = new PaytmOrder(paramMap);
Service.initialize(Order,null);
Service.startPaymentTransaction(ReviewBooking.this, true, true, new PaytmPaymentTransactionCallback() {
#Override
public void someUIErrorOccurred(String inErrorMessage) {
// Some UI Error Occurred in Payment Gateway Activity.
// // This may be due to initialization of views in
// Payment Gateway Activity or may be due to //
// initialization of webview. // Error Message details
// the error occurred.
}
#Override
public void onTransactionResponse(Bundle inResponse) {
Log.d("LOG", "Payment Transaction : " + inResponse);
String response=inResponse.getString("RESPMSG");
if (response.equals("Txn Successful."))
{
new ConfirmMerchent().execute();
}else
{
Toast.makeText(getApplicationContext(),response,Toast.LENGTH_SHORT).show();
}
Toast.makeText(getApplicationContext(), "Payment Transaction response "+inResponse.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void networkNotAvailable() {
// If network is not
// available, then this
// method gets called.
}
#Override
public void clientAuthenticationFailed(String inErrorMessage) {
// This method gets called if client authentication
// failed. // Failure may be due to following reasons //
// 1. Server error or downtime. // 2. Server unable to
// generate checksum or checksum response is not in
// proper format. // 3. Server failed to authenticate
// that client. That is value of payt_STATUS is 2. //
// Error Message describes the reason for failure.
}
#Override
public void onErrorLoadingWebPage(int iniErrorCode,
String inErrorMessage, String inFailingUrl) {
}
// had to be added: NOTE
#Override
public void onBackPressedCancelTransaction() {
// TODO Auto-generated method stub
}
#Override
public void onTransactionCancel(String inErrorMessage, Bundle inResponse) {
Log.d("LOG", "Payment Transaction Failed " + inErrorMessage);
Toast.makeText(getBaseContext(), "Payment Transaction Failed ", Toast.LENGTH_LONG).show();
}
});
}
JsonParser Class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
HttpURLConnection urlConnection = null;
// variable to hold context
private Context context;
// constructor
public JSONParser(Context context){
this.context=context;
}
public JSONObject makeHttpRequest(String url,String method,String params) {
// boolean isReachable =Config.isURLReachable(context);
// Making HTTP request
try {
String retSrc="";
char current = '0';
URL url1 = new URL(url);
// check for request method
HttpURLConnection urlConnection = (HttpURLConnection) url1.openConnection();
if (method == "POST") {
// request method is POST
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setFixedLengthStreamingMode(params.getBytes().length);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
out.print(params);
out.close();
}
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
byte[] bytes = new byte[10000];
StringBuilder x = new StringBuilder();
int numRead = 0;
while ((numRead = in.read(bytes)) >= 0) {
x.append(new String(bytes, 0, numRead));
}
retSrc=x.toString();
jObj = new JSONObject(retSrc);
} catch (Exception e) {
e.printStackTrace();
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Connectivity issue. Please try again later.", Toast.LENGTH_LONG).show();
}
});
return null;
}finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return jObj;
}
}
and parameter values should be same both time.
Generating Checksum is quite easy.
Just get the Paytm App Checksum Kit from Github.
Extract the downloaded kit and put it in your server. If you are using a local server using xampp then the path would be c:/xampp/htdocs/paytm. I would recommend renaming the folder name to paytm or a small name.
Inside the kit there is a folder named lib. Inside this folder you will find a file named config_paytm.php, Open this file and put your Paytm Merchant Key here.
Now you can use the file generateChecksum.php to generate checksum.
Remember you need to pass every parameter that you will pass with transaction.
Below you can see a retrofit api code sample to send POST request to generateChecksum.php.
//this is the URL of the paytm folder that we added in the server
//make sure you are using your ip else it will not work
String BASE_URL = "http://192.168.101.1/paytm/";
#FormUrlEncoded
#POST("generateChecksum.php")
Call<Checksum> getChecksum(
#Field("MID") String mId,
#Field("ORDER_ID") String orderId,
#Field("CUST_ID") String custId,
#Field("CHANNEL_ID") String channelId,
#Field("TXN_AMOUNT") String txnAmount,
#Field("WEBSITE") String website,
#Field("CALLBACK_URL") String callbackUrl,
#Field("INDUSTRY_TYPE_ID") String industryTypeId
);
This part is very important you have to send all the parameters. And order_id should be unique everytime.
Source: Paytm Integration in Android Example
You need to pass only 8 param for checksum generation from SDK 2.0 and later. On Earlier version you need to pass email and mobile number too. Now there is no use of these param. First upload PHP file on your server and change the merchant key on config.php file inside lib folder. Now from android use can use retrofit or volley or httpconnection request to get checksum from your server. Here i am using Httpconnection (in this code JSONParse is a separate java class to call httpconnection). You can get reference on this link -http://www.blueappsoftware.in/android/blog/paytm-integration-sdk-2-1-android/
public class sendUserDetailTOServerdd extends AsyncTask<ArrayList<String>, Void, String> {
private ProgressDialog dialog = new ProgressDialog(checksum.this);
private String orderId , mid, custid, amt;
String url ="http://www.blueappsoftware.com/payment/payment_paytm/generateChecksum.php";
String varifyurl = // "https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=<ORDER_ID>"; //
"https://pguat.paytm.com/paytmchecksum/paytmCallback.jsp";//
String CHECKSUMHASH ="";
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
// initOrderId();
orderId ="KK100343"; // NOTE : order id must be unique
mid = "blueap01867059473586"; // CREATI42545355156573
custid = "KKCUST0342";
}
protected String doInBackground(ArrayList<String>... alldata) {
// String url ="http://xxx.co.in/generateChecksum.php";
JSONParser jsonParser = new JSONParser(checksum.this);
String param=
"MID="+mid+
"&ORDER_ID=" + orderId+
"&CUST_ID="+custid+
"&CHANNEL_ID=WEB&TXN_AMOUNT=100&WEBSITE=www.blueappsoftware.in"+"&CALLBACK_URL="+ varifyurl+"&INDUSTRY_TYPE_ID=Retail";
Log.e("checksum"," param string "+param );
JSONObject jsonObject = jsonParser.makeHttpRequest(url,"POST",param);
// yaha per checksum ke saht order id or status receive hoga..
Log.e("CheckSum result >>",jsonObject.toString());
if(jsonObject != null){
Log.e("CheckSum result >>",jsonObject.toString());
try {
CHECKSUMHASH=jsonObject.has("CHECKSUMHASH")?jsonObject.getString("CHECKSUMHASH"):"";
Log.e("CheckSum result >>",CHECKSUMHASH);
} catch (JSONException e) {
e.printStackTrace();
}
}
return CHECKSUMHASH;
}
#Override
protected void onPostExecute(String result) {
// jab run kroge to yaha checksum dekhega
///ab service ko call krna hai
Log.e(" setup acc "," signup result " + result);
if (dialog.isShowing()) {
dialog.dismiss();
}}
Step 2) now onPostExceute method you have checksum as result. It's time to call paytm staging service and call start transaction. Below is code to call paytm service
PaytmPGService Service =PaytmPGService.getStagingService();
// when app is ready to publish use production service
// PaytmPGService Service = PaytmPGService.getProductionService();
// now call paytm service here
//below parameter map is required to construct PaytmOrder object, Merchant should replace below map values with his own values
Map<String, String> paramMap = new HashMap<String, String>();
//these are mandatory parameters
// ye sari valeu same hon achaiye
//MID provided by paytm
paramMap.put("MID", mid);
paramMap.put("ORDER_ID", orderId);
paramMap.put("CUST_ID", custid);
paramMap.put("CHANNEL_ID", "WEB");
paramMap.put("TXN_AMOUNT", "100");
paramMap.put("WEBSITE", "www.blueappsoftware.in");
paramMap.put("CALLBACK_URL" ,varifyurl);
//paramMap.put( "EMAIL" , "abc#gmail.com"); // no need
// paramMap.put( "MOBILE_NO" , "9144040888"); // no need
paramMap.put("CHECKSUMHASH" ,CHECKSUMHASH);
//paramMap.put("PAYMENT_TYPE_ID" ,"CC"); // no need
paramMap.put("INDUSTRY_TYPE_ID", "Retail");
PaytmOrder Order = new PaytmOrder(paramMap);
Log.e("checksum ", paramMap.toString());
Service.initialize(Order,null);
// start payment service call here
Service.startPaymentTransaction(checksum.this, true, true, checksum.this );
what is new ConfirmMerchent().execute();
and in docs
after merchent verify check again this uri for payment confirmation
https://secure.paytm.in/oltp/HANDLER_INTERNAL/TXNSTATUS

How to send parameters with url and get response in android

I am performing login task and getting data from PHP server in json format. In response, I am getting a 'success' tag that containing User-ID
like this {"message":"You have been successfully login","success":"75"}
I get that value as "uid" in the same activity and move to next page. Now in next page, I want to check user profile. For that, I have to pass that "uid" as 'params' with url and get value from server. But don't understand how to do that.
In next activity page I am creating asyncTask to perform action.
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(PROFILE_URL, "GET",params);
// Check your log cat for JSON reponse
Log.d("Profile JSON: ", json.toString());
try {
// profile json object
profile = json.getJSONObject(TAG_PROFILE);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Now I have to set the 'uid' in the place of params.
Use intent to pass data,
Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("UID", uId);
startActivity(intent)
Use intent, but if you want to keep your uid for a long time , you can use SharedPrefferences
Method 1:
Class A {
String UID = "3";
public static void main(String[] args){
ClassB.setUid(3);
}
}
Class B {
public static String uid;
public static setUid(String id){
uid = id;
}
}
Method 2:
Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("U_ID", uId);
startActivity(intent)
Beware about static variables, programmers dont usually like them and call them evil.
If what you're trying to do is transfer data from one activity to another, try adding an extra to your intent. After you've created the intent to launch the next page, add something like
intent.putExtra("uid", uid);
to add the uid as an extra. And on the next page, you can retrieve this data by
Intent intent = getIntent();
int uid = intent.getIntExtra("uid", defaultvalue);
In case you need to pass parameters along with GET method, you can simply add the respective values to the url:
public void getData(String uid) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.yoursite.com/script.php?uid=" + uid);
HttpResponse response = httpclient.execute(httpget);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
If you want to pass parameters with POST method the code is a bit more complex:
public void postData(String uid) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>;
nameValuePairs.add(new BasicNameValuePair("uid", uid));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
In both cases you can get server response as stream:
InputStream s = response.getEntity().getContent();
The easiest way to get response body as a String is to call:
String body = EntityUtils.toString(response.getEntity());
Of course, there are numerous other ways to achive what you desire.
There are two ways to pass parameters with Get request.
http://myurl.com?variable1=value&variable2=value2
Passing arguments as headers in request.
As HttpClient is now deprecated in the API 22, so you should use the Google Volley https://developer.android.com/training/volley/simple.html
Adding parameters using volley library as
/**
* This method is used to add the new JSON request to queue.
* #param method - Type of request
* #param url - url of request
* #param params - parameters
* #param headerParams - header parameters
* #param successListener - success listener
* #param errorListener - error listener
*/
public void executeJSONRequest(int method, String url, final JSONObject params, final HashMap<String, String> headerParams,
Response.Listener successListener,
Response.ErrorListener errorListener) {
JsonObjectRequest request = new JsonObjectRequest(method, url, params,
successListener, errorListener) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
if (headerParams != null)
return headerParams;
else
return super.getHeaders();
}
};
// Add request to queue.
addRequestToQueue(request);
}

Access token validation from Google, Google+ Sign-in Android

I want to fetch an access-token from Google and then send it to my server as a JSON object*.
On server I want to validate the access token and then store essential user information.
My server is written in Node.js. How to do that?
#Override
public void onConnected(Bundle connectionHint) {
Log.v(TAG, "Connected. Yay!");
findViewById(R.id.sign_in_button).setVisibility(View.INVISIBLE);
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String code;
Bundle appActivities = new Bundle();
appActivities.putString(GoogleAuthUtil.KEY_REQUEST_VISIBLE_ACTIVITIES,
"http://schemas.google.com/AddActivity");
String scopes = "oauth2:" + Scopes.PLUS_LOGIN + " " + Scopes.PLUS_ME;
try {
code = GoogleAuthUtil.getToken(
AuthenticationActivity.this, // Context context
mPlusClient.getAccountName(), // String accountName
scopes, // String scope
appActivities // Bundle bundle
);
} catch (UserRecoverableAuthException e) {
// Recover
code = null;
//System.out.println(e.printStackTrace());
AuthenticationActivity.this.startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (Exception e) {
throw new RuntimeException();
}
return code;
}
#Override
protected void onPostExecute(String token) {
/* if(token!=null)
{
Log.i(TAG, "Access token retrieved:" + token);
//SharedPreference = getApplicationContext().getSharedPreferences("TokenPreference", 0);
//editor = SharedPreference.edit();
editor.putString("access_token",token);
editor.commit();
} */
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://gumbox1.cloudapp.net:3000");
JSONObject data = new JSONObject();
data.put("data", token);
HttpEntity entity = new StringEntity(data.toString());
BufferedReader reader = new BufferedReader(new InputStreamReader(client.execute(post).getEntity().getContent()));
String response = reader.readLine();
Log.e("response", response);
}
catch(Exception e)
{ Log.e("",e.toString());
}
}
};
task.execute();
}
You need to pass auth token to https://www.googleapis.com/oauth2/v1/userinfo?access_token= url. It will return the JSON data for user information.
You should do like
private static final String USER_INFO_URL = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=";
URL url = new URL(USER_INFO_URL + code);
con = (HttpURLConnection) url.openConnection();
InputStream is = con.getInputStream();
// Now convert into String and then into Json

how to parse json response from webservice url and parse it as url in android

I have an application in that i called webservice using this link,I have one webservice Url and another Url is getting as response from that url.I need to use that url as
public static final String TIME_CENTRAL_SERVER = "http://accounts.myexample.com/Services"; in the place of
"http://accounts.myexample.com/Services" i need to parse my json response.
I have check for that in google but couldn't get any answer can anyone help me regarding this, Thanks in advance.
If anyone have queries ask me.
First webservice call is like below
RestClient client = new RestClient(LOGIN_URL);
client.AddParam("accountType", "GOOGLE");
client.AddParam("source", "tboda-widgalytics-0.1");
client.AddParam("Email", _username);
client.AddParam("Passwd", _password);
client.AddParam("service", "analytics");
client.AddHeader("GData-Version", "2");
try {
client.Execute(RequestMethod.POST);
} catch (Exception e) {
e.printStackTrace();
}
String response = client.getResponse();
After parsing the response, if you want to do another Web Service call, just create another object of RestClient with different URL and Parameters and call execute method, like below,
RestClient client1 = new RestClient(GET_INFO_URL);
client1.AddParam("userid", "123");
try {
client1.Execute(RequestMethod.POST);
} catch (Exception e) {
e.printStackTrace();
}
String response1 = client1.getResponse();
finally i solved my issue with guidance of my team head below is the code which we have used in constants.java class
public static final String GET_CENTRAL_SERVER = String.format("%s/AccountService/security/ValidateAccess", TIMEMACHINE_ACCOUNTS_SERVER);
and add code snippet in serversync.java class
public String getCentralServer(Context context, String serial_number) throws Exception{
// TODO Auto-generated method stub
WebServiceClient client = new WebServiceClient(Constants.GET_CENTRAL_SERVER);
client.addParam("accesscode", String.valueOf(serial_number));
client.addParam("type", "2");
client.Execute(RequestMethod.GET);
String response = client.getResponse();
if (response != null){
response = response.replaceAll("\\\\/", "/");
response = response.replace("\"", "");
response = response.replace("\n","");
response = "http://" + response;
return response;
}
return null;
}

Categories

Resources