Volley POST Request receiving wrong results - android

I have hosted my API on an online server. When I am testing it using the Postman app for chrome , its returning me the right results (ie. the details of the user from the database) But the below Volley request is getting wrong results (ie. Required Parameters missing);
Screenshot of Postman Request
Volley Request
private void loginUser(final String username, final String password){
String URL_REGISTER = "http://www.h8pathak.orgfree.com/jobs/login.php";
pDialog.setMessage("Logging in...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
int result = jObj.getInt("result");
if(result==1){
session.setLogin(true);
JSONObject jObj2 = jObj.getJSONObject("user");
Intent i = new Intent(LoginActivity.this, EmployerActivity.class);
i.putExtra("username", jObj2.getString("username"));
i.putExtra("email", jObj2.getString("email"));
startActivity(i);
finish();
Toast.makeText(LoginActivity.this, jObj.getString("message"), Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(LoginActivity.this, jObj.getString("message"),Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(LoginActivity.this, volleyError.getMessage(), Toast.LENGTH_SHORT).show();
hideDialog();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq);
}
The PHP Code to receive request params and return the appropriate response.
if(isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
//Get the details from the database and echo in a json response
}
else{
$message = "Required parameters missing!";
$response['result']=0;
$response['message']=$message;
echo json_encode($response);
}
What could be the possible mistake?

Something is wrong with your server configuration: http://www.h8pathak... is not responding as expected, but http://h8pathak... works. The latter is used in your postman example, use it in you Android code and it will work there too.

WWW is the answer. This must be a bug. It goes to the URL and runs it but does not POST.
http://www.example.com/myphpfile.php is wrong.
http://example.com/myphpfile.php is right.

Related

My response in Volley request always get into Error Listener

i am using volly for json response this is my java code i tried every thing but unable to find error in it. it always go to Error Listener.i really dont know why my response goes to error listener any body help me please thanks in advance
private void userLoign() {
name = Name_Et.getText().toString();
email = Email_Et.getText().toString();
password = Password_Et.getText().toString();
Toast.makeText(MainActivity.this, "enter in userlogin", Toast.LENGTH_SHORT).show();
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String URL = "added-platters.000webhostapp.com/application/index.php";
Toast.makeText(MainActivity.this, "enter in Volley", Toast.LENGTH_SHORT).show();
StringRequest myReq = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
int success = jObj.getInt("value");
Log.e("value in success", String.valueOf(success));
Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
Log.i("myTag", e.toString());
Toast.makeText(MainActivity.this, "Parsing error", Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("myTag", error.toString());
Toast.makeText(MainActivity.this, "Server Error", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "Register");
params.put("name", name);
params.put("email", email);
params.put("password", password);
params.put("lat", "1234");
params.put("log", "1234");
return params;
}
};
myReq.setRetryPolicy(new DefaultRetryPolicy(
20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
));
myReq.setShouldCache(false);
queue.add(myReq);
}
and this is my json response in php
{"value":"Record Inserted Successfully"}
The Problem is URL Protocol not specified
String URL = "added-platters.000webhostapp.com/application/index.php";
to
String URL = "http://added-platters.000webhostapp.com/application/index.php";

Getting this error while using android volley(POST Method) : java.net.ConnectException: Failed to connect to /192.168.0.2:4000

I am trying to send a POST request to a node js server using Volley in android. For some reason it is throwing java.net.ConnectException: Failed to connect to /192.168.43.252:4000 exception. I have ensured that my URL is not localhost. I am putting the IPv4 address which i am getting from ipconfig. What could be the possible reasons for my exception and what is the solution ?
Following is the code I am using :
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressBar.setVisibility(View.GONE);
try {
//converting response to json object
JSONObject obj = new JSONObject(response);
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getInt("id"),
userJson.getString("username"),
userJson.getString("email"),
userJson.getString("gender")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
return params;
}
};
//Following is part of my code from node server
//in routes
app.post('/login', AuthenticateLogin.validateUser)
//in AuthenticateLogin.js
exports.validateUser = function(req, res, next){
console.log('Hello');
res.sendStatus(200);
}

app returning empty Toast

i am getting an empty Toast as response when i try to register a user to my sql database and no useful error hint is thrown in the logcat.
please what could possibly be the cause of this ?
registerProcess
private void registerProcess(final String name, final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
Functions.REGISTER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response);
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
Functions logout = new Functions();
logout.logoutUser(getApplicationContext());
Bundle b = new Bundle();
b.putString("email", email);
Intent i = new Intent(RegisterActivity.this, EmailVerify.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtras(b);
startActivity(i);
pDialog.dismiss();
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("message");
Toast.makeText(getApplicationContext(),errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
web service
/**
* Adding new user to mysql database
* returns user details
*/
public function storeUser($fname, $lname, $email, $uname, $password) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$result = mysql_query("INSERT INTO users(unique_id, firstname, lastname, email, username, encrypted_password, salt, created_at) VALUES('$uuid', '$fname', '$lname', '$email', '$uname', '$encrypted_password', '$salt', NOW())");
// check for successful store
if ($result) {
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
// return user details
return mysql_fetch_array($result);
} else {
return false;
}
}
There seems to be no error in the code, as far as I can see.
You should check the response you get with curl and see, what is returned.
to get the response from your web service you don't need JSON since you're doing a POST request by Volley. Your toast is empty because simply you're interpreting the response wrong and the objects like this one String errorMsg = jObj.getString("message"); will be empty.
To get the response you should do like this :
if (response.equalsIgnoreCase("yourResponseFromTheWebService")) {
...
Toast
} else if (response.equalsIgnoreCase("OtherPossibleResponse")){
....
Toast
} else{
....
Toast
}
EDIT :
I managed to spot two things in your web service code.
1- why are you trying to get informations from the server of the same user when you just sent them from your app. That doesn't make sense. You should attach your data as extra to your intent as you did with the email.
2- Volley expects a String type response and you giving him different formats at the same time.
So this a modified version of your code :
Web service :
public function storeUser($fname, $lname, $email, $uname, $password) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$result = mysql_query("INSERT INTO users(unique_id, firstname, lastname, email, username, encrypted_password, salt, created_at) VALUES('$uuid', '$fname', '$lname', '$email', '$uname', '$encrypted_password', '$salt', NOW())");
// check for successful store
if ($result) {
echo "successful";
} else {
echo "notsuccessful";
}
}
Android
private void registerProcess(final String name, final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
Functions.REGISTER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response);
hideDialog();
if (response.equalsIgnoreCase("successful")) {
Functions logout = new Functions();
logout.logoutUser(getApplicationContext());
Bundle b = new Bundle();
//add other informations you need like name ect..
b.putString("email", email);
Intent i = new Intent(RegisterActivity.this, EmailVerify.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtras(b);
startActivity(i);
pDialog.dismiss();
finish();
} else if(response.equalsIgnoreCase("notsuccessful")) {
Toast.makeText(getApplicationContext(),"new user wasn't registered successfully", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
NOTE :
if you wanna know the error from your Mysql request don't show it on your app, just check it in your browser.
I hope this works for you

BasicNetwork.performRequest: Unexpected response code 500 for

I have this Login Java code in my Android Studio:
private void loginUser(){
pd = ProgressDialog.show(LoginActivity.this, "", "Loading...");
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
System.out.println("JSON RESPONSE: " + jsonResponse.toString());
boolean success = jsonResponse.getBoolean("success");
if (success) {
launchHomeScreen();
pd.dismiss();
Toast.makeText(LoginActivity.this,"Welcome back " + username,Toast.LENGTH_LONG).show();
SharedPreferences sharedPref = getSharedPreferences("loginDatas", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.apply();
}
else {
loginButton.setBackgroundColor(0x73000000);
Toast.makeText(LoginActivity.this,"Wrong Username or Password!",Toast.LENGTH_LONG).show();
pd.dismiss();
}
}
catch (JSONException e) {
loginButton.setBackgroundColor(0x73000000);
e.printStackTrace();
pd.dismiss();
Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loginButton.setBackgroundColor(0x73000000);
pd.dismiss();
System.out.println("Error: " + error);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<>();
params.put(KEY_USERNAME,username);
params.put(KEY_PASSWORD,password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
But everytime I get this error in my Android Log console:
I tried so many things but everytime I try it, I get back: 04-20 07:44:18.463 3326-2366/com.lolol.gg E/Volley: [294] BasicNetwork.performRequest: Unexpected response code 500 for http://lollipop.xyz/login.php
04-20 07:44:18.514 3326-3326/com.lolol.ggI/System.out: Error: com.android.volley.ServerError
Has anybody an Idea, how to fix my problem? Because I tried many things...It won't work anyway...
The weired thing is:
I have tested the server code very often it works. When I try the javacode with the url for my localwampserver it works....When I try it with the url from my hostinger server it didn't work...In the 2 servers are the same codes...
Getting an HTTP response code of 500 means that your app successfully contacted the server, but the server itself has encountered an unexpected error.
Contact your backend maintainer to see why the server is misbehaving, this most probably isn't an issue you can fix in your Android code.
Looks like a server side error, first make sure your service work (using Postman for instance or any rest client).
If the problem persists you could try using Retrofit2 instead of Volley (which I personally prefer)
I have used stringrequest to get response from the server and pass your params.
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {JSONObject jsonObject = new JSONObject(response);
} catch (JSONException ignored) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError) {
}
}
}) {
#Override
public Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("name", "Droider");
return headers;
}
#Override
public Priority getPriority() {
return Priority.IMMEDIATE;
}
};
ApplicationController.getInstance().addToRequestQueue(stringRequest);

Android volley gives BasicNetwork.performRequest: Unexpected response code 415

While doing a POST request with android volley, My serverside consumes json type in request header, I am facing error 415. Though i have set the headers here by overriding getHeaders method, I am facing this unusual error while making the request.
can any body help me here?
I have also provided the source code below:
private void registerUser( final String email,
final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(email, uid, created_at);
Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
//params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
#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;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

Categories

Resources