API calling when phone local language is Arabic in android - android

I am working on an android project, in which i have to call APIs in english when mobile local language is Arabic. i am not getting API URl String in English.
My API calling file(PackageapiCall.class) is as follows:
package com.example.app.roamer.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Looper;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.app.roamer.Constant;
import com.example.app.roamer.R;
import com.example.app.roamer.activities.SplashScreen;
import com.example.app.roamer.app.AppController;
import com.example.app.roamer.fragments.AlltripsFragment;
import com.example.app.roamer.helper.DateFormatsHelper;
import com.example.app.roamer.fragments.TaTripsFragment;
import com.example.app.roamer.models.AllTrips;
import com.example.app.roamer.tasks.GenerateTokenOperation;
import com.example.app.roamer.tasks.ParsingOperation;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static com.example.app.roamer.activities.HomeActivity.TAG;
/**
* Created by manish on 22-12-2016.
*/
public class PackageApicalls {
private Request.Priority priority = Request.Priority.HIGH;
Context ctx;
private List<AllTrips.TripsBean> allTripsByMobileUserIDNewData, allTripsByMobileUserIDNewData1;
AlltripsFragment alltripsFragment;
TaTripsFragment taTripsFragment;
Boolean splashScreenApiCall=false;
SharedPreferences sharedPreferences;
private int mobileUserId;
public PackageApicalls(Context ctx, AlltripsFragment alltripsFragment) {
this.ctx=ctx;
this.alltripsFragment=alltripsFragment;
}
public PackageApicalls(Context ctx, TaTripsFragment taTripsFragment) {
this.ctx=ctx;
this.taTripsFragment=taTripsFragment;
}
public PackageApicalls(Context ctx) {
this.ctx=ctx;
}
public void getalltripdetails() {
// String gettodaysdate="02-02-2016";
DateFormatsHelper dateFormatsHelper = new DateFormatsHelper();
String gettodaysdate = dateFormatsHelper.gettodaysdate();
sharedPreferences = ctx.getSharedPreferences(Constant.MyPREFERENCES, Context.MODE_PRIVATE);
mobileUserId = sharedPreferences.getInt("mobileUserId", 0);
//mobileUserId=1;
String url = ctx.getResources().getString(R.string.alltrips_api_url,mobileUserId,gettodaysdate);
Log.d(TAG, "manish-url-packageapicalls"+url);
StringRequest postRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (Looper.myLooper() == Looper.getMainLooper()) {
Log.d(TAG, "main thread-true");
} else {
Log.d(TAG, "main thread-false");
}
// response
Log.d("Response", response);
allTripsByMobileUserIDNewData = parsejson(response);
// setupui(allTripsByMobileUserIDNewData);
Log.d("manishbutola", "onResponse: New Data arrived");
// pDialog.hide();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.d("manishbutola", "getalltripdetailserror => " + error.toString());
new GenerateTokenOperation(ctx).execute();
if(new GenerateTokenOperation(ctx).getStatus()== AsyncTask.Status.FINISHED){
getalltripdetails();
}
/*if(GenerateTokenOperation(ctx).Status == AsyncTask.Status.FINISHED){
// START NEW TASK HERE
}*/
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
sharedPreferences = ctx.getSharedPreferences(Constant.MyPREFERENCES, Context.MODE_PRIVATE);
String token_value = sharedPreferences.getString("token", null);
String authorizedtoken = "bearer" + " " +token_value;
//params.put("User-Agent", "Nintendo Gameboy");
Log.d("packageApiCalls", "authorizedtoken: "+ authorizedtoken);
params.put("Authorization", authorizedtoken);
return params;
}
#Override
public Priority getPriority() {
return priority;
}
};
AppController.getInstance().addToRequestQueue(postRequest);
//return parsejson;
// List<AllTrips.TripsBean> allTrips=db.getAllTripsByMobileUserID(1);
}
private List<AllTrips.TripsBean> parsejson(String response) {
try {
if(Constant.splashScreenApiCall){
new ParsingOperation(ctx).execute(response);
}
else{
new ParsingOperation(ctx,alltripsFragment).execute(response);
}
} catch (Exception e) {
e.printStackTrace();
}
return allTripsByMobileUserIDNewData1;
}
}
My `gettodaydate` method as follows:
public String gettodaysdate(){
DateFormat formatter;
formatter = new SimpleDateFormat("MM-dd-yyyy",Locale.ENGLISH);
String result = formatter.format(new Date());
/*DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
Date date = new Date();*/
// return dateFormat.format(date);
return result;
}
and finally my string.xml :
<string name="alltrips_api_ta_url" translatable="false">http://roamer.techmaster.in/Rest/api/GetAgentTrips?agentId="%1$d"&isPreviousTrip=false&date="%2$s"</string>
I ma getting log cat as:
Unexpected response code 400 for http://roamer.techmaster.in/Rest/api/GetTrips?mobileUserId=١&isPreviousTrip=false&date=02-14-2017
as i am seeing that mobileUserId is 1 and it is going to convert in url in Arabic when url going to hit to server. app going to crash.Please help me out.Thanks.

After struggle i got an idea and it worked, it is:
i change int to string like:
String userId = String.valueOf(mobileUserId); and then i do
<string name="alltrips_api_ta_url" translatable="false">http://base_url/trips?agentId="%1$d"&isPreviousTrip=false&date="%2$s"</string>
to
<string name="alltrips_api_ta_url" translatable="false">http://base_url/GetAgentTrips?agentId="%1$s"&isPreviousTrip=false&date="%2$s"</string>
and then i put
String url = ctx.getResources().getString(R.string.alltrips_api_url,userId ,gettodaysdate);

in your getHeaders() add the Content-Type
#Override
public Map<String,String> getHeaders() throws AuthFailureError {
HashMap<String,String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
Also override getBodyContentType() and return "application/x-www-form-urlencoded; charset=UTF-8";
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}

Related

How to show image fetched from mysqldatabase to imageview

Here this is the layout in which I have to set the image of the user who successfully logged in
and I have saved the url of the image in the table where all the details of the users are there....
So what I was trying is I am fetching the url of the image from the database and then tried to set it into imageview.. I have checked that the url is comming to the variable...
so as you can see in the above image it is not setting the image in imageview but when I assign the url first to the imgurl variable at the time of defining the variable then it works fine...
I don't know why this is happening... am I doing anything wrong or is there any other way to achieve this?
This is the code of the file...
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class Dashboard extends AppCompatActivity {
TextView usrname;
ImageView profileimg;
public static String imgurl = "";//here
/**
* Shared Preferences
**/
SharedPreferences sharedPreferences;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
public static final String Email = "emailKey";
/**
* Shared Preferences
**/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
profileimg = findViewById(R.id.iv_display_image);
usrname = findViewById(R.id.tv_username);
/**Shared Preferences**/
sharedPreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
/**Shared Preferences**/
//fetching session data
String name = sharedPreferences.getString(Name, "0");
usrname.setText(name);
fetchimg(name);
LoadImage loadImage = new LoadImage(profileimg);
Log.d("Oncreate img url", imgurl);
loadImage.execute(imgurl);
}
private void fetchimg(String name) {
StringRequest request = new StringRequest(Request.Method.POST, "https://**url**//fetchimg.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.startsWith("Here")) {
String urlstr = getUrl(response, "Here ");
seturl(urlstr);
Log.d("urlstr value:", urlstr);
} else {
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
Log.d("vOLLEY ERROR", response.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("vOLLEY ERROR", error.getMessage().toString());
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("login_name", "xxxxx");
params.put("login_pass", "xxxxx");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(Dashboard.this);
requestQueue.add(request);
}
private void seturl(String urlstr) {
this.imgurl = urlstr;
Log.d("Image url set inside seturl", imgurl);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.dashboardmenu, menu);
return true;
}
public void openeditprofile(View view) {
startActivity(new Intent(this, EditProfileActivity.class));
}
private class LoadImage extends AsyncTask<String, Void, Bitmap> {
ImageView imageView;
public LoadImage(ImageView profileimg) {
this.imageView = profileimg;
}
#Override
protected Bitmap doInBackground(String... strings) {
String urlLink = strings[0];
Bitmap bitmap = null;
try {
InputStream inputStream = new java.net.URL(urlLink).openStream();
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
profileimg.setImageBitmap(bitmap);
}
}
public static String getUrl(String string, String word) {
// Check if the word is present in string
// If found, remove it using removeAll()
if (string.contains(word)) {
// To cover the case
// if the word is at the
// beginning of the string
// or anywhere in the middle
String tempWord = word + " ";
string = string.replaceAll(tempWord, "");
// To cover the edge case
// if the word is at the
// end of the string
tempWord = " " + word;
string = string.replaceAll(tempWord, "");
}
// Return the resultant string
return string;
}
}
You are fetching image asynchronously, your Asynctask execute will be called with empty imgUrl as it not already fetched, move AsyncTask execution code in onResponse of fetching
private void fetchimg(String name) {
StringRequest request = new StringRequest(Request.Method.POST, "https://**url**//fetchimg.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.startsWith("Here")) {
String urlstr = getUrl(response, "Here ");
seturl(urlstr);
//here the url is ready to consume
Log.d("urlstr value:", urlstr);
//load the image now
LoadImage loadImage = new LoadImage(profileimg);
Log.d("Oncreate img url", imgurl);
loadImage.execute(imgurl);
} else {
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
Log.d("vOLLEY ERROR", response.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("vOLLEY ERROR", error.getMessage().toString());
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("login_name", "xxxxx");
params.put("login_pass", "xxxxx");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(Dashboard.this);
requestQueue.add(request);
}
use **Glide** to display Image from Url into image view.
You have to add glide lib in app-level build.gradle file.
implementation 'com.github.bumptech.glide:glide:4.12.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
Glide.with(this).load(url)
.transform(CenterCrop(), RoundedCorners(radius))
.placeholder(R.drawable.drawable_image_placeholder)
.error(R.drawable.drawable_image_placeholder)
.into(ivProfile)
drawable_image_placeholder is the default imageview that displays
when getting the error to load the image. ivProfile is imageview .

Android volley token changes every request

I want to get the results about imei adresses after my inquiry on the inquiry site. The site has token input during the query and I can get this token as follows. But when i run the second volley queue i soppose the token changes and the result doesn't come. How can I solve this problem. The site that i questioned the imei adress and my codes are below.
package com.myapp.query;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import android.os.Bundle;
import android.widget.Toast;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import androidx.appcompat.app.AppCompatActivity;
public class imeiSorgulama extends AppCompatActivity {
StringRequest stringRequest;
RequestQueue queue;
String token, tag, value, tag2, value2, result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_imei_sorgulama);
queue = Volley.newRequestQueue(this);
final String url = "https://www.turkiye.gov.tr/imei-sorgulama";
stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
tag = "<input type=\"hidden\" name=\"token\" value=\"";
value = response.substring(response.indexOf(tag) + tag.length());
token = value.substring(0, value.indexOf("\""));
try {
token = URLEncoder.encode(token,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
imeiQuery();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(imeiSorgulama.this, error+"", Toast.LENGTH_SHORT).show();
}
}
);
queue.add(stringRequest);
}
private void imeiQuery() {
final String url = "https://www.turkiye.gov.tr/imei-sorgulama?submit";
stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
tag2 = "<dl class=\"compact\">";
value2 = response.substring(response.indexOf(tag2) + tag2.length());
result = value2.substring(0, value2.indexOf("</dl>"));
Toast.makeText(imeiSorgulama.this, result+"", Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(imeiSorgulama.this, error+"", Toast.LENGTH_SHORT).show();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("txtImei", "545454545454545");
params.put("token=", token);
return params;
}
};
queue.add(stringRequest);
}
}

How to login with outlook/microsoft using webview?

There are libraries available for login with outlook using a browser (especially chrome browser i.e. MSAL android library ) OR ADAL, but I don't want to log-in with chrome because in my device chrome is not available (Its custom OS flashed in an android device).
I have tried on my end also but its not working as this code is giving access token but not useful to call graph API
here is my code
package learn2crack.weboauth2;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends Activity implements View.OnClickListener {
private static final String TAG = "MainActivity";
//Change the Scope as you need
WebView web;
Button auth;
SharedPreferences pref;
TextView Access;
String authCode = "";
private Dialog auth_dialog;
private Button authEbay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getSharedPreferences("AppPref", MODE_PRIVATE);
Access =(TextView)findViewById(R.id.Access);
auth = (Button)findViewById(R.id.auth);
auth.setOnClickListener(this);
authEbay = (Button)findViewById(R.id.auth_ebay);
auth.setOnClickListener(this);
authEbay.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.auth:
auth(Constants.OUTLOOK.USER_AGENT,
Constants.OUTLOOK.OAUTH_URL,
Constants.OUTLOOK.REDIRECT_URI,
Constants.OUTLOOK.CLIENT_ID,
Constants.OUTLOOK.OAUTH_SCOPE);
break;
case R.id.auth_ebay:
auth(Constants.EBAY.USER_AGENT,
Constants.EBAY.OAUTH_URL,
Constants.EBAY.REDIRECT_URI,
Constants.EBAY.CLIENT_ID,
Constants.EBAY.OAUTH_SCOPE);
break;
}
}
private void auth(String userAgent, String oauthUrl, String redirectUri, String clientId,
String oauthScope) {
final Dialog auth_dialog;
// TODO Auto-generated method stub
auth_dialog = new Dialog(MainActivity.this);
auth_dialog.setContentView(R.layout.auth_dialog);
web = (WebView)auth_dialog.findViewById(R.id.webv);
web.getSettings().setJavaScriptEnabled(true);
WebSettings webSettings = web.getSettings();
web.getSettings().setUserAgentString(userAgent);
webSettings.setSupportMultipleWindows(true);
web.loadUrl(oauthUrl+"?redirect_uri="+
redirectUri+"&response_type=code&client_id="+
clientId+"&scope="+ oauthScope);
web.setWebViewClient(new WebViewClient() {
boolean authComplete = false;
Intent resultIntent = new Intent();
#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);
if (url.contains("?code=") && authComplete != true) {
Uri uri = Uri.parse(url);
authCode = uri.getQueryParameter("code");
callGraphAPI(authCode);
Log.i("", "CODE : " + authCode);
authComplete = true;
resultIntent.putExtra("code", authCode);
auth_dialog.dismiss();
Toast.makeText(getApplicationContext(),"Authorization Code is: "
+authCode, Toast.LENGTH_SHORT).show();
}else if(url.contains("error=access_denied")){
Log.i("", "ACCESS_DENIED_HERE");
Toast.makeText(getApplicationContext(), "Error Occured",
Toast.LENGTH_SHORT).show();
auth_dialog.dismiss();
}
}
});
auth_dialog.show();
auth_dialog.setTitle("Authorize Learn2Crack");
auth_dialog.setCancelable(true);
}
private void callGraphAPI(final String code)
{
Log.d(TAG, "Starting volley request to graph");
/* Make sure we have a token to send to graph */
RequestQueue queue = Volley.newRequestQueue(this);
JSONObject parameters = new JSONObject();
try {
parameters.put("key", "value");
} catch (Exception e) {
Log.d(TAG, "Failed to put parameters: " + e.toString());
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, Constants.OUTLOOK.MSGRAPH_URL,
parameters,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
/* Successfully called graph, process data and send to UI */
Log.d(TAG, "Response: " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap();
headers.put("Authorization", "Bearer " + authCode);
return headers;
}
};
Log.d(TAG, "Adding HTTP GET to Queue, Request: " + request.toString());
request.setRetryPolicy(new DefaultRetryPolicy(
3000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
}
}
anybody please suggeest how to get proper access token after login with microsoft/outlook using webview.
Thanks in advance.

Pass params Using GET method using volley library

How can we pass params from editText to url using request.GET method.
Actually I am trying to pass an email address as parameter to a api which should b attached to api-url .
I came to know from here that getParams() is not called on the GET method, so it seems you'll have to add it to the URL before you send the request.
suggest me any solution to achieve the task ..
when i pass REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser?email=ameer#novatoresols.com";
it return success=true response as expected because is registered user
but if i set REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser and pass the params (get value from edittext and use params.put in getparams() method ).response is always success=false i.e params is not attached to url
here is my code.
package com.example.mts3.hammadnewsapp;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.provider.SyncStateContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class RegisterActivity extends AppCompatActivity {
Button btn_verf;
EditText et_Email;
String u_emails,stat;
AlertDialog.Builder alertDialog;
private static final String TAG = "LoginActivity";
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Context context;
// public static String firstname, lastname, useremail, userphone, userpass;
// String REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser?email=ameer#novatoresols.com";
String REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
btn_verf=findViewById(R.id.btn_reg_send_vf_code);
et_Email=findViewById(R.id.et_reg_email);
alertDialog =new AlertDialog.Builder(RegisterActivity.this);
// u_emails=et_Email.getText().toString().trim();
btn_verf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callApi();
}
});
}
private void callApi() {
// Log.e(TAG, "onClick: ");
/*if (!utility.isInternetConnected()) {
Toast.makeText(LoginActivity.this, "Please check your internet connection.", Toast.LENGTH_SHORT).show();
return;
}*/
// dialog = utility.showProgressDialog(LoginActivity.this, "Please wait");
final String email = et_Email.getText().toString().trim();
// Log.e(TAG, "onClick: email = " + email );
// JSONObject params = new JSONObject();
/*
HashMap<String,String> params=new HashMap<>();
params.put("email",email);*/
/*try {
// params.getString("email");
params.put("email",email);
Log.e(TAG, "getParams: param = " + "try of put prams");
} catch (JSONException e){
Log.e(TAG, "getParams: param = " + "catch of put prams");
e.printStackTrace();
}*/
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, REG_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(RegisterActivity.this, "REsponse: " + response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> params=new HashMap<>();
// params.put("email",email);
params.put("email",email);
return params;
}
}; queue.add(stringRequest);
}
}
As suggested by #Puneet worked for me which is as :
getParams is only called for POST requests. GET requests don't have a body and hence, getParams is never called. For a simple request like yours just add the parameters to your URL and use that constructed URL to make that request to your server (REG_URL + "?email=" + email).
To pass the parameters, you need to create a class for the key-value pairs.
1) Create a class KeyValuePair with two fields key and value with appropriate constructor and getter-setter methods.
2) Now, for each parameter, you need to create an object of this class, i.e., for a key username with value user#gmail.com, the object would be new KeyValuePair("username", "user#gmail.com").
3) Now, you need to create a List to store these parameters and pass this list to the below method with your base url,
public static String generateUrl(String baseUrl, List<KeyValuePair> params) {
if (params.size() > 0) {
for (KeyValuePair parameter: params) {
if (parameter.getKey().trim().length() > 0)
baseUrl += "&" + parameter.getKey() + "=" + parameter.getValue();
}
}
return baseUrl;
}
4) Pass this baseUrl to your Request.

Awkward session error with magento cookie parsing in Android App

I am working on an Android app which uses sessions by managing cookies from an API based on magento backend.
On the app side, I am using Volley Library for network request. I have successfully got the network response and from that I have fetched the "Set-Cookie" value. Now when I am attaching this cookie to the header but the server doesn't validate my session.
The strange thing is I tried to request the same JSON request from a rest client and then used the cookie from that and added to the header as a static value and then I was provided session access. I completely have no idea regarding what is going on. Why the cookies from rest client is working while the cookie value from my network response doesn't.
Here is my SignIn Activity code where I am doing a login json request and storing the cookie value.
package com.paaltao.activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.github.mrengineer13.snackbar.SnackBar;
import com.paaltao.R;
import com.paaltao.classes.MyApp;
import com.paaltao.classes.PersistentCookieStore;
import com.paaltao.classes.ProgressWheel;
import com.paaltao.classes.SharedPreferenceClass;
import com.paaltao.logging.L;
import com.paaltao.network.VolleySingleton;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import static com.paaltao.extras.Keys.UserCredentials.*;
import static com.paaltao.extras.urlEndPoints.BASE_URL;
import static com.paaltao.extras.urlEndPoints.LOGIN;
import static com.paaltao.extras.urlEndPoints.UAT_BASE_URL;
public class SignInActivity extends AppCompatActivity {
private static final String SET_COOKIE_KEY = "Set-Cookie";
private static final String COOKIE_KEY = "Cookie";
private static final String SESSION_COOKIE = "sessionid";
Button SignUpBtn;
Button SignInBtn;
ProgressWheel progressBar;
EditText email, password;
TextView forgotPassword;
String emailId,accessToken,api_ver,token,firstName,lastName,cookie,newCookie;
Boolean login_success;
SharedPreferenceClass preferenceClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
Toolbar toolbar = (Toolbar) this.findViewById(R.id.app_bar);
toolbar.setTitleTextColor(Color.WHITE);
toolbar.setBackgroundColor(getResources().getColor(R.color.transparent));
this.setSupportActionBar(toolbar);
this.setTitle("Sign in");
initiate();
onItemClick();
}
public void initiate() {
SignUpBtn = (Button) findViewById(R.id.signUpBtn);
email = (EditText) findViewById(R.id.email_field);
password = (EditText) findViewById(R.id.password_field);
SignInBtn = (Button) findViewById(R.id.signInBtn);
forgotPassword = (TextView) findViewById(R.id.forgot_password);
progressBar = (ProgressWheel)findViewById(R.id.action_progress);
preferenceClass = new SharedPreferenceClass(getApplicationContext());
}
public boolean validationCheck() {
if (email.getText().toString().length() == 0)
email.setError("Please provide your email. Your email must be in the format abc#xyz.com");
else if (password.getText().toString().length() == 0)
password.setError("Please provide a password");
else return true;
return false;
}
public void onItemClick() {
SignInBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validationCheck()) {
sendJsonRequest();
}
}
});
SignUpBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SignInActivity.this, SignUpActivity.class);
startActivity(intent);
}
});
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SignInActivity.this, ForgotPasswordActivity.class);
startActivity(intent);
}
});
}
public static String getRequestUrl() {
return UAT_BASE_URL
+ LOGIN;
}
public void sendJsonRequest() {
progressBar.setVisibility(View.VISIBLE);
final JSONObject jsonObject = new JSONObject();
final JSONObject signIn = new JSONObject();
try {
jsonObject.put("email", email.getText().toString());
jsonObject.put("password", password.getText().toString());
signIn.put("emailSignIn", jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, getRequestUrl(), signIn, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
if (progressBar.getVisibility() == View.VISIBLE) {
progressBar.setVisibility(View.GONE);
}
parseJSONResponse(jsonObject);
//Calling the Snackbar
Log.e("response", jsonObject.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (progressBar.getVisibility() == View.VISIBLE) {
progressBar.setVisibility(View.GONE);
}
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
new SnackBar.Builder(SignInActivity.this)
.withMessage("No Internet Connection!")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
} else if (volleyError instanceof AuthFailureError) {
//TODO
} else if (volleyError instanceof ServerError) {
//TODO
} else if (volleyError instanceof NetworkError) {
//TODO
} else if (volleyError instanceof ParseError) {
//TODO
}
}
}) {
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
// since we don't know which of the two underlying network vehicles
// will Volley use, we have to handle and store session cookies manually
// MyApp.get().checkSessionCookie(response.headers);
L.m(response.headers.toString());
L.m(Arrays.toString(response.data));
L.m(response.headers.get("Set-Cookie"));
preferenceClass.saveCookiee(response.headers.get("Set-Cookie"));
cookie = response.headers.get("Set-Cookie");
String[] splitCookie = cookie.split(";");
String[] splitSessionId = splitCookie[0].split("=");
newCookie = splitSessionId[1];
//cookie = response.headers.values().toString();
Log.e("split",newCookie);
preferenceClass.saveCookie(newCookie);
return super.parseNetworkResponse(response);
}
#Override
public Map<String, String> getHeaders ()throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
// MyApp.get().addSessionCookie(headers);
return headers;
}
}
;
requestQueue.add(jsonObjectRequest);
}
public void parseJSONResponse(JSONObject jsonObject) {
if (jsonObject == null || jsonObject.length() == 0) {
return;
}
try {
JSONObject dataObject = jsonObject.getJSONObject(KEY_DATA);
JSONObject signInObject = dataObject.getJSONObject(KEY_SIGN_IN);
JSONObject accessTokenObject = signInObject.getJSONObject(KEY_ACCESS_TOKEN);
JSONObject errorNodeObject = dataObject.getJSONObject(KEY_ERROR_NODE);
if(dataObject.has(KEY_VENDOR)){
if (dataObject.isNull(KEY_VENDOR)){
return;
}
else {JSONObject vendorObject = dataObject.getJSONObject(KEY_VENDOR);
if(vendorObject != null){
String vendor_login = vendorObject.getString(KEY_HAS_SHOP);
if(vendor_login != null && vendor_login.contains("true")){
preferenceClass.saveVendorLoginSuccess(vendor_login);
}}}
}
emailId = signInObject.getString(KEY_EMAIL);
firstName = signInObject.getString(KEY_FIRST_NAME);
lastName = signInObject.getString(KEY_LAST_NAME);
login_success = signInObject.getBoolean(KEY_USER_LOGIN_SUCCESS);
preferenceClass.saveFirstName(firstName);
preferenceClass.saveLastName(lastName);
preferenceClass.saveUserEmail(emailId);
if(accessTokenObject.has(KEY_TOKEN)){
token = accessTokenObject.getString(KEY_TOKEN);}
String errorCode = errorNodeObject.getString(KEY_ERROR_CODE);
String message = errorNodeObject.getString(KEY_MESSAGE);
if (login_success){
Log.e("TAG",login_success.toString());
if (token!= null && token.length()!=0){
preferenceClass.saveAccessToken(token);
preferenceClass.saveUserEmail(emailId);
Intent intent = new Intent(SignInActivity.this,HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
else{
Log.e("TAG",login_success.toString());
new SnackBar.Builder(SignInActivity.this)
.withMessage("Username or Password is Incorrect!")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
and this is the code for the fragment where I am doing a check session test with the stored cookie received from network response (Note: I replaced the cookie with the one I got from rest client and it worked!!)
package com.paaltao.fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpClientStack;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.HttpStack;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.github.mrengineer13.snackbar.SnackBar;
import com.paaltao.R;
import com.paaltao.activity.AddressActivity;
import com.paaltao.activity.IntroPageActivity;
import com.paaltao.activity.PaaltaoInfo;
import com.paaltao.activity.EditProfileActivity;
import com.paaltao.classes.MyApp;
import com.paaltao.classes.PersistentCookieStore;
import com.paaltao.classes.SharedPreferenceClass;
import com.paaltao.logging.L;
import com.paaltao.network.VolleySingleton;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import cn.pedant.SweetAlert.SweetAlertDialog;
import static com.paaltao.extras.Keys.UserCredentials.KEY_ACCESS_TOKEN;
import static com.paaltao.extras.Keys.UserCredentials.KEY_DATA;
import static com.paaltao.extras.Keys.UserCredentials.KEY_ERROR_CODE;
import static com.paaltao.extras.Keys.UserCredentials.KEY_ERROR_NODE;
import static com.paaltao.extras.Keys.UserCredentials.KEY_MESSAGE;
import static com.paaltao.extras.Keys.UserCredentials.KEY_SIGN_OUT;
import static com.paaltao.extras.urlEndPoints.BASE_URL;
import static com.paaltao.extras.urlEndPoints.SIGN_OUT;
import static com.paaltao.extras.urlEndPoints.UAT_BASE_URL;
//This is a user account fragment.
public class AccountFragment extends Fragment {
private static final String SET_COOKIE_KEY = "Set-Cookie";
private static final String COOKIE_KEY = "Cookie";
private static final String SESSION_COOKIE = "sessionid";
RelativeLayout accountLink,my_address,signOut;
View view;
String accessToken;
TextView firstName,lastName,about,terms,privacy,notificationSettings;
SharedPreferenceClass preferenceClass;
SweetAlertDialog dialog;
Context context;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_account, container, false);
initialize();
onItemClick();
return view;
}
public static String getRequestUrl() {
return UAT_BASE_URL
+ SIGN_OUT;
}
public void sendJsonRequest(){
final JSONObject jsonObject = new JSONObject();
final JSONObject signOut = new JSONObject();
try{
jsonObject.put("accessToken","67drd56g");
signOut.put("signOut", jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,getRequestUrl(),signOut,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.e("error", jsonObject.toString());
Log.e("json", signOut.toString());
parseJSONResponse(jsonObject);
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
new SnackBar.Builder(getActivity())
.withMessage("No Internet Connection!")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
} else if (volleyError instanceof AuthFailureError) {
//TODO
} else if (volleyError instanceof ServerError) {
//TODO
} else if (volleyError instanceof NetworkError) {
//TODO
} else if (volleyError instanceof ParseError) {
//TODO
}
}
});
requestQueue.add(jsonObjectRequest);
}
public void parseJSONResponse(JSONObject jsonObject) {
if (jsonObject == null || jsonObject.length() == 0) {
return;
}
try {
JSONObject dataObject = jsonObject.getJSONObject(KEY_DATA);
JSONObject signOutObject = jsonObject.getJSONObject(KEY_SIGN_OUT);
JSONObject errorNodeObject = dataObject.getJSONObject(KEY_ERROR_NODE);
accessToken = signOutObject.getString(KEY_ACCESS_TOKEN);
String errorCode = errorNodeObject.getString(KEY_ERROR_CODE);
String message = errorNodeObject.getString(KEY_MESSAGE);
if (errorCode.equals("200")){
preferenceClass.clearAccessToken();
preferenceClass.clearFirstName();
preferenceClass.clearLastName();
preferenceClass.clearUserEmail();
Log.e("accessToken",accessToken);
Intent intent = new Intent(getActivity(),IntroPageActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
getActivity().finish();
}
else{
new SnackBar.Builder(getActivity())
.withMessage("Error in signing out")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void sendJsonRequest1(){
final JSONObject jsonObject = new JSONObject();
final JSONObject sessionCheck = new JSONObject();
try{
jsonObject.put("accessToken","67drd56g");
sessionCheck.put("checkSession", jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,getRequestUrl1(),sessionCheck,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.e("error", jsonObject.toString());
Log.e("json", sessionCheck.toString());
Log.e("url",getRequestUrl());
L.m(jsonObject.toString());
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
} else if (volleyError instanceof AuthFailureError) {
//TODO
} else if (volleyError instanceof ServerError) {
//TODO
} else if (volleyError instanceof NetworkError) {
//TODO
} else if (volleyError instanceof ParseError) {
//TODO
}
}
})
{
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
// since we don't know which of the two underlying network vehicles
// will Volley use, we have to handle and store session cookies manually
// MyApp.get().checkSessionCookie(response.headers);
//L.m(response.headers.toString());
return super.parseNetworkResponse(response);
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
String sessionId = preferenceClass.getCookie();
Log.e("cOOOKIE","frontend="+sessionId);
Log.e("sessionid","frontend=7fgenogpffjvvmdg1gf439hta7");
// headers.put(COOKIE_KEY,"frontend="+sessionId);
headers.put(COOKIE_KEY,"frontend=e7qfldgsnf7aop381a8vk3b866");
return headers;
}};
requestQueue.add(jsonObjectRequest);
}
private String getRequestUrl1() {
return UAT_BASE_URL+"checkSession";
}
public void initialize(){
accountLink = (RelativeLayout)view.findViewById(R.id.account_link);
my_address = (RelativeLayout)view.findViewById(R.id.my_address);
signOut = (RelativeLayout)view.findViewById(R.id.signOut);
preferenceClass = new SharedPreferenceClass(getActivity());
firstName = (TextView)view.findViewById(R.id.firstName);
lastName = (TextView)view.findViewById(R.id.lastName);
about = (TextView)view.findViewById(R.id.about);
terms = (TextView)view.findViewById(R.id.terms);
privacy = (TextView)view.findViewById(R.id.privacy);
if(preferenceClass.getFirstName() != null)
firstName.setText(preferenceClass.getFirstName());
if(preferenceClass.getLastName() != null)
lastName.setText(preferenceClass.getLastName());
notificationSettings = (TextView)view.findViewById(R.id.notification_settings);
}
public void onItemClick(){
notificationSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendJsonRequest1();
}
});
accountLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), EditProfileActivity.class));
}
});
my_address.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), AddressActivity.class));
}
});
signOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
confirmSignOut();
}
});
about.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), PaaltaoInfo.class);
intent.putExtra("page","about_paaltao");
startActivity(intent);
}
});
terms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), PaaltaoInfo.class);
intent.putExtra("page","terms");
startActivity(intent);
}
});
privacy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), PaaltaoInfo.class);
intent.putExtra("page","privacy_policy");
startActivity(intent);
}
});
}
public void confirmSignOut(){
dialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.NORMAL_TYPE);
dialog.setTitleText("Signout")
.setContentText("Are you sure you want to sign out?")
.setConfirmText("Yes")
.setCancelText("No")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sDialog) {
sendJsonRequest();
}
})
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sDialog) {
dialog.cancel();
}
})
.show();
}
}
There is no structural difference between the rest client cookie and the one recieved in app:
rest client cookie : frontend=48b1i38fgls4d0241mp6d6rrr0
app side cookie : frontend=86n349m3patu37eud00ntobd90
Thanks in advance. It will be a life saver if some one can help.

Categories

Resources