Pass params Using GET method using volley library - android

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.

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 .

JSON data not returning

I have written a code to access the below api and get the corresponding values of namaz timings, but the onResponse method is not getting invoked. I have given internet permissions in the android manifest file. I am new to Android, please help.
While Installing app is not asking for internet permissions though I mentioned it in manifest file.
import android.app.ProgressDialog;
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.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class NamazTiming extends AppCompatActivity {
private TextView fazarId, zoharid, asarid, magribid, ishaid, location;
private RequestQueue mQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.namaz_timing);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Namaz Timings");
fazarId = findViewById(R.id.fazarid);
zoharid = findViewById(R.id.zoharid);
asarid = findViewById(R.id.asarid);
magribid = findViewById(R.id.magribid);
ishaid = findViewById(R.id.ishaid);
location = findViewById(R.id.location);
Button locationbutton = findViewById(R.id.locationbutton);
mQueue = Volley.newRequestQueue(this);
locationbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
}
});
}
private void jsonParse() {
//String loc = location.getText().toString().trim();
String url ="https://muslimsalat.com/uravakonda.json?key=ba8d0b5ba55c6db3cebbe3fefd6090f8";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(NamazTiming.this, "Entered onresponse", Toast.LENGTH_SHORT).show();
try {
Toast.makeText(NamazTiming.this, "Entered into TRY", Toast.LENGTH_SHORT).show();
String Fazar = response.getJSONArray("items").getJSONObject(0).get("fajr").toString();
String Zohr = response.getJSONArray("items").getJSONObject(0).get("dhuhr").toString();
String Asar = response.getJSONArray("items").getJSONObject(0).get("asr").toString();
String Magrib = response.getJSONArray("items").getJSONObject(0).get("maghrib").toString();
String Isha = response.getJSONArray("items").getJSONObject(0).get("isha").toString();
fazarId.setText(Fazar);
zoharid.setText(Zohr);
asarid.setText(Asar);
magribid.setText(Magrib);
ishaid.setText(Isha);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(NamazTiming.this, "Please enter the lccation name", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(NamazTiming.this, "Please enter the lccation name", Toast.LENGTH_SHORT).show();
}
});
}
You need to add your request object to the Volley queue (in your case, mQueue) in order for the request to be executed.
Example:
mQueue.add(request);
Internet permission is normal permission so the android system will not ask internet permission.
You just call this line:
mQueue.add(request);
end of the request.
Add below line after errorListener method at end of your request
mQueue.add("your request type");

Volley perform too many uncontrolled retries

I have a serious problem.
I have a small app for a restaurant to manage the creation of orders, update, and so. Waiters use an android tablet to serve to the customers.
The thing is that since a week or so, I realized that tickets tend to duplicate items. After some research and diving into the logs, I realized that many times, when I call an AsyncTask to make a request to the server, it doesn't send ONE request, it sends several requests instead.
For that reason, if I call the "addItemToOrder" service four times, it will add four items instead of just one.
Here is my code. This is a "generic GET Async Task" that I call. It has an url, it may or not has some parameters, and it just creates a volley request that sends to the server. As you can see, it has 0 retries and, before you can ask, I just made sure that this AT is not being called more than once:
package es.vdevelop.tpvmobile.asynctask;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.widget.Toast;
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.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bugfender.sdk.Bugfender;
import org.json.JSONException;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
import es.vdevelop.tpvmobile.Constants;
import es.vdevelop.tpvmobile.ErrorHelper;
import es.vdevelop.tpvmobile.FunctionsHelper;
abstract class GenericGetAsyncTask extends AsyncTask<Void, Void, Void> {
private static final String TAG = "DEBUG GenericGetAT";
Handler h;
WeakReference<Context> context;
String auxURL;
HashMap<String, String> postParams;
String query;
GenericGetAsyncTask(WeakReference<Context> context, Handler h) {
this.auxURL = "";
this.context = context;
this.h = h;
this.postParams = new HashMap<>();
this.query = "";
}
#Override
protected Void doInBackground(final Void... params) {
if (!FunctionsHelper.isConnected(context.get())) {
h.sendEmptyMessage(ErrorHelper.HANDLER_NO_INTERNET_ERROR);
Bugfender.d(TAG, "No internet connection");
ErrorHelper.mostrarError(context.get(), ErrorHelper.HANDLER_NO_INTERNET_ERROR, TAG);
return null;
}
String urlParcial = Constants.getUrl(context.get());
if (urlParcial.equals("")) {
h.sendEmptyMessage(ErrorHelper.HANDLER_FALTA_URL);
Bugfender.d(TAG, "Falta url");
ErrorHelper.mostrarError(context.get(), ErrorHelper.HANDLER_URL_INCORRECTA, TAG);
return null;
}
int metodo;
String url;
if (query == null || query.equals("")) {
url = urlParcial + this.auxURL;
metodo = Request.Method.POST;
} else {
url = urlParcial + this.auxURL + "?" + this.query;
metodo = Request.Method.GET;
}
Bugfender.d(TAG, "url -> " + url);
final RequestQueue queue = Volley.newRequestQueue(context.get());
final StringRequest request = new StringRequest(metodo, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
onResultRetrieved(response);
} catch (JSONException e) {
Bugfender.d(TAG, "Hubo un error de json en onResponse -> " + e.toString());
h.sendEmptyMessage(ErrorHelper.HANDLER_RESPUESTA_INCORRECTA);
ErrorHelper.mostrarError(context.get(), ErrorHelper.HANDLER_JSON, TAG);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Bugfender.d(TAG, "Error recibido del servidor -> " + error.toString());
ErrorHelper.mostrarError(context.get(), ErrorHelper.HANDLER_RESPUESTA_INCORRECTA, TAG);
Toast.makeText(context.get(), "Error realizando llamada http -> " + error.toString(), Toast.LENGTH_SHORT).show();
h.sendEmptyMessage(ErrorHelper.HANDLER_ERROR);
}
}) {
#Override
protected Map<String, String> getParams() {
return postParams;
}
#Override
public Priority getPriority() {
return Priority.IMMEDIATE;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(2000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
return null;
}
protected abstract void onResultRetrieved(String result) throws JSONException;
}
After that, then I just have to inherit from this generic AT with just some bit of code to make a simple request, just as you can see here in this "UpdateTicketAT":
package es.vdevelop.tpvmobile.asynctask;
import android.content.Context;
import android.os.Handler;
import com.bugfender.sdk.Bugfender;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
import es.vdevelop.tpvmobile.Constants;
import es.vdevelop.tpvmobile.ErrorHelper;
import es.vdevelop.tpvmobile.Functions;
public class UpdateTicketAsyncTask extends GenericGetAsyncTask {
private static final String TAG = "DEBUG UpdateTicketAT";
public UpdateTicketAsyncTask(WeakReference<Context> context, Handler h, String json) {
super(context, h);
this.auxURL = "actualizar_ticket.php";
this.postParams.put("ticket", json);
Bugfender.d(TAG, "Ticket que vamos a enviar -> " + json);
}
#Override
protected void onResultRetrieved(String response) throws JSONException {
Bugfender.d(TAG, "Respuesta obtenida del servidor -> " + response);
JSONObject result = new JSONObject(response);
int codigo = result.getInt("codigo");
if (codigo == 0) {
h.sendEmptyMessage(Constants.handlerOk);
Bugfender.d(TAG, "Ticket actualizado correctamente");
} else {
h.sendEmptyMessage(Constants.handlerError);
ErrorHelper.mostrarError(context.get(), codigo, TAG);
}
}
}
I can't find out what is happening here. Am I doing something wrong?
One important thing is that the calls to the server may not be all made in a row. I mean, I make a request, I get the response, and maybe a minute or two later, the request is made again!
I just can be aware of this by looking into the server logs..
I don't know what's happening here..
Anyway, thanks in advance!
I can see two ways to answer your question or not:
First: i don`t like your "0" in your DefaultRetryPolicy line, try to put some like this:
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(TIMEOUT_SERVICE,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
The first parameter is timeout, second is max retries (yes i know, you know that but check that is 1) and the last one is DefaultRetryPolicy.DEFAULT_BACKOFF_MULT ( again i know, blah blah, but check that is 1.0f) or put literal.
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(TIMEOUT_SERVICE,
1, 1.0f));
Second: Can you only set more time in your time out.
I hope this help you.

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.

BasicNetwork.performRequest: Unexpected response code 301

So i´m trying to login on my app and when i click the login button after inserting the username and password this error shows up in the android studio at the run tab on the bottom toolbar in the left corner:
E/Volley: [11996] BasicNetwork.performRequest: Unexpected response code 301 "MYURL"
with my site link and nothing more.
you can learn more about the error HTTP 301 here!
Here is my code:
login.java
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class login extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mView = inflater.inflate(R.layout.login, container, false);
final EditText etUtilizador = mView.findViewById(R.id.etUtilizador);
final EditText etPassword = mView.findViewById(R.id.etPassword);
final Button btLogin = mView.findViewById(R.id.btLogin);
Button btlink = mView.findViewById(R.id.btlink);
btlink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(getActivity(), registar.class);
getActivity().startActivity(registerIntent);
}
});
btLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = etUtilizador.getText().toString();
final String password = etPassword.getText().toString();
Response.Listener<String> responselistener=new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject jsonResponse= null;
try {
jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String name = jsonResponse.getString("name");
int age = jsonResponse.getInt("age");
Intent intent;
intent = new Intent(getContext(), utilizador.class);
intent.putExtra("name", name);
intent.putExtra("age", age);
intent.putExtra("username", username);
login.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
loginrequest loginRequest = new loginrequest(username, password, responselistener);
RequestQueue queue = Volley.newRequestQueue(getActivity());
queue.add(loginRequest);
}
});
return mView;
}
}
loginrequest.java
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class loginrequest extends StringRequest {
private static final String LOGIN_REQUEST_URL = "http://elabora.pt/login.php";
private Map<String, String> params;
public loginrequest(String username, String password, Response.Listener<String> listener) {
super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("username", username);
params.put("password", password);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
If you need more classes or the android manifest comment below and i edit the post.
I already have the login.php to connect to the database at the file manager and everything.
If you can help me understanding why this error is showing up i would be gratefull.
HTTP code 301 means "moved permanently". This means the URL you're trying to reach is no longer there. I had the same problem when my site implemented SSL. They redirected all request from http:// to https:// using an .htaccess file in the server, so the address in the Android app had to be changed accordingly, since it's not going to accept the redirection. You should change your LOGIN_REQUEST_URL variable to:
private static final String LOGIN_REQUEST_URL = "https://elabora.pt/login.php";
Hope this helps (it did solve my problem, though)
I had the same problem. Unexpected response code 301
I was using https://example.com but it was redirecting to https://www.example.com via .htaccess
Changing to https://www.example.com in the app code solved my problem.
Try to open the url in the browser here you can see the exactly redirected URL copy this to your code.
You can specify a http folder in your host or sever instead of auto redirect to https when you use volley.
It seems Volley can not handle https request.

Categories

Resources