BasicNetwork.performRequest: Unexpected response code 301 - android

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.

Related

Something went wrong, Android Studio + Volley

i'm very beginner in this problem.
i following the tutorials from youtube make a database for user register, i use localhost and put the php file into htdocs and it's succes but when i tried to put the php file into 000webhost file manager. the result is 'something went wrong' it should be 'Succesfully Registered'. i dont know what should i do because there's no error in logcat. i'm sure there's no error in php file because i've matched it with the real source code.
Example Error Image
Thank you in advance.
here is my code
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
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.util.HashMap;
import java.util.Map;
public class Register extends AppCompatActivity {
private EditText etName, etEmail, etPassword, etReenterPassword;
private TextView tvStatus;
private String URL = "https://db4image.000webhostapp.com/login/register.php";
private String name, email, password, reenterPassword;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etName = findViewById(R.id.name);
etEmail = findViewById(R.id.email);
etPassword = findViewById(R.id.password);
etReenterPassword = findViewById(R.id.repass);
tvStatus = findViewById(R.id.tvStatus);
name = email = password = reenterPassword = "";
}
public void daftarCok (View view) {
name = etName.getText().toString().trim();
email = etEmail.getText().toString().trim();
password = etPassword.getText().toString().trim();
reenterPassword = etReenterPassword.getText().toString().trim();
if(!password.equals(reenterPassword)){
Toast.makeText(this, "Password Mismatch", Toast.LENGTH_SHORT).show();
}
else if(!name.equals("") && !email.equals("") && !password.equals("")){
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("success")) {
tvStatus.setText("Successfully registered.");
Intent inten = new Intent(Register.this, MainActivity.class);
startActivity(inten);
}
else if (response.equals("failure")) {
tvStatus.setText("Something went wrong!");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.toString().trim(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> data = new HashMap<>();
data.put("name", name);
data.put("email", email);
data.put("password", password);
return data;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
public void login(View view) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
This is my register.php
<?php
if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password'])){
require_once "conn.php";
require_once "validate.php";
$name = validate($_POST['name']);
$email = validate($_POST['email']);
$password = validate($_POST['password']);
$sql = "INSERT INTO users VALUES ('', '$name', '$email', '" . md5($password) . "')";
if(!$conn->query($sql)){
echo "failure";
}else{
echo "success";
}
}
?>

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 SSL Exception during registration into onilne mysql database form android app

I have tried a lot of codes and techniques. But i could not find any solution. I also posted my problem on stackover flow but could not get any response. Thats why i am again posting this question.
I am new to android. I have a website which in now running online with secure SSL certificate. I have designed an android app where people will perform their registration. I want to save all their data into online mysql database of my website. I am using VOLLEY LIBRARY. When i click on register button from my android app, it is showing me this error:
com.android.volley.NoConnectionError: SSLException: SSL handshake aborted: ssl=0x77754ed0: I/O error during system call, Connection reset by peer.
Please Help me. I am begginer to android. I cant solve this problem.
This is my Main Activity.java Code:
package com.myapper.hasee.server;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import android.widget.EditText;
import android.widget.Button;
import java.util.HashMap;
import java.util.Map;
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 javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class MainActivity extends AppCompatActivity {
// Creating EditText.
EditText FirstName, LastName, Email ;
// Creating button;
Button InsertButton;
// Creating Volley RequestQueue.
RequestQueue requestQueue;
// Create string variable to hold the EditText Value.
String FirstNameHolder, LastNameHolder, EmailHolder ;
// Creating Progress dialog.
ProgressDialog progressDialog;
// Storing server url into String variable.
String HttpUrl = "https://bomvibe.com/folder_name/myfile.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Assigning ID's to EditText.
FirstName = (EditText) findViewById(R.id.editTextFirstName);
LastName = (EditText) findViewById(R.id.editTextLastName);
Email = (EditText) findViewById(R.id.editTextEmail);
// Assigning ID's to Button.
InsertButton = (Button) findViewById(R.id.ButtonInsert);
// Creating Volley newRequestQueue .
requestQueue = Volley.newRequestQueue(MainActivity.this);
progressDialog = new ProgressDialog(MainActivity.this);
// Adding click listener to button.
InsertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Showing progress dialog at user registration time.
progressDialog.setMessage("Please Wait, We are Inserting Your Data on Server");
progressDialog.show();
// Calling method to get value from EditText.
GetValueFromEditText();
// Creating string request with post method.
StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String ServerResponse) {
// Hiding the progress dialog after all task complete.
progressDialog.dismiss();
// Showing response message coming from server.
Toast.makeText(MainActivity.this, ServerResponse, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
// Hiding the progress dialog after all task complete.
progressDialog.dismiss();
// Showing error message if something goes wrong.
Toast.makeText(MainActivity.this, volleyError.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Creating Map String Params.
Map<String, String> params = new HashMap<String, String>();
// Adding All values to Params.
params.put("first_name", FirstNameHolder);
params.put("last_name", LastNameHolder);
params.put("email", EmailHolder);
return params;
}
};
// Creating RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
}
});
}
// Creating method to get value from EditText.
public void GetValueFromEditText(){
FirstNameHolder = FirstName.getText().toString().trim();
LastNameHolder = LastName.getText().toString().trim();
EmailHolder = Email.getText().toString().trim();
}
}
Hope i will get a good solution at this time. Thanks in advance experts:)

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.

How to use facebook access token as a string in graph api

Actually i want to post on my page as a page not as a user using facebook sdk in android app but the problem is page "AccessToken" which i retrieve from graph request is in String and now i cannot use it in an other graph request. it says String cannot converted to AccessToken.
Here is my code.
package com.mak.masimmak.pageshare;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import org.json.JSONException;
import org.json.JSONObject;
public class sharePage extends AppCompatActivity {
Button shareButton;
public String PageId;
String PageAccessToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share_page);
shareButton = (Button) findViewById(R.id.shareButton);
shareButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
if(getIntent().getExtras() != null) {
Bundle extras = getIntent().getExtras();
PageId = extras.getString("PageId");
/* make the API call */
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/"+PageId+"?fields=access_token",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
try {
JSONObject data = response.getJSONObject();
PageAccessToken = data.getString("access_token");
PostOnPage();
} catch (JSONException e) {
Toast.makeText(sharePage.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
).executeAsync();
}
}
});
}
public void PostOnPage(){
Bundle params = new Bundle();
params.putString("message", "This is a test message");
/* make the API call */
new GraphRequest(
/* Problem is here the PageAccessToken is in String How to use this string token here? */
(AccessToken) PageAccessToken,
"/"+PageId+"/feed",
params,
HttpMethod.POST,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
}
}
).executeAsync();
}
}
I search the problem in google and i found something..
public AccessToken(String accessToken, String applicationId, String userId, Collection permissions, Collection declinedPermissions, AccessTokenSource accessTokenSource, Date expirationTime, Date lastRefreshTime)
But i don't know how use this or implement this in my code.
I found the solution of my own question.
You can convert AccessToken from String format to Facebook AccessToken format using this line of code.
AccessToken PageAT = new AccessToken(PageAccessToken, AccessToken.getCurrentAccessToken().getApplicationId(), AccessToken.getCurrentAccessToken().getUserId(), AccessToken.getCurrentAccessToken().getPermissions(), null, AccessTokenSource.FACEBOOK_APPLICATION_NATIVE, AccessToken.getCurrentAccessToken().getExpires(), null);
Then this PageAT will work fine in your new Graph Request..

Categories

Resources