I am trying to put in a delete account option in my application, however when I try to delete the account I am not getting a respsonse from the web server.
Instead I get the error:
org.json.JSONException: End of input at character 0 of
I have tried to change the request method to DELETE however I am not too familiar with android and databases so I am not sure if that would work.
I am not sure whether the problem lies with the php or the java code, when I run the debugger in android studio the String response returns:
response: ""
php:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$id = $_POST['id'];
require 'conn.php';
$sql = "DELETE * FROM Patients WHERE patientID='$id'";
if(mysqli_query($conn, $sql)){
$result['success'] = "1";
$result['message'] = "success";
echo json_encode($result);
mysqli_close($conn);
} else {
$result["success"] = "0";
$result["message"] = "Error!";
echo json_encode($result);
mysqli_close($conn);
}
}
?>
Java delete method:
private void deleteAccount() {
final String name = this.name.getText().toString().trim();
final String lName = this.lName.getText().toString().trim();
final String dob = this.dob.getText().toString().trim();
final String email = this.email.getText().toString().trim();
final String password = this.password.getText().toString().trim();
final String passwordConf = this.cPassword.getText().toString().trim();
final String id = getID;
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_DELETE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if(success.equals("1")){
Toast.makeText(EditAccount.this, "Account Deleted", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Toast.makeText(EditAccount.this, "Error: "+e.toString(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(EditAccount.this, "Error: "+error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("id", id);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
I expect the toast to pop up and say account deleted but instead I get the error message stated at the top.
p.s. this is just a prototype so I am not worried about security at the moment.
Thanks!
Whatever the issue might be, I am going to take a guess and say if($_SERVER['REQUEST_METHOD']=='POST') is the root of your issue.
Your request may be sent wrong to the server and the method is not recognized as POST which would explain a "" response since you do not offer an alternative to what should happen at the condition failing.
Send a bad request response (400) back and you will have the ability to troubleshoot this issue in your Java code... PHP is fine.
if($_SERVER['REQUEST_METHOD']=='POST') { /* ... */ }
else {
http_response_code(400);
// exit('Bad request method.');
// or for a json response:
echo json_encode([
'success' => "0",
'message' => "Bad Request Method used."
]);
}
Also, I have to say... Security should always be a concern... It does not take but a few more lines of code to filter the user request, and make your query a bit more secure via prepared statements. It's more of an issue of habits; one day you might forget a query here or there.
Related
I'm Trying to list machines which are related to the user of the application by sending the username and password to the webpage mentioned in the code verifying the account and then sending back the information of the machines in my database.
the PHP well but the username and password are not being sent.
here is the code for the request:
private void getServerResponse(String username,String password) throws IOException {
String urlS = "http://10.0.2.2/send/sendmachines.php";
RequestQueue RQ= Volley.newRequestQueue(this);
JsonArrayRequest array_request = new JsonArrayRequest(Request.Method.POST, urlS, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
TextView proof =findViewById(R.id.proof);
for(int i=0; i<response.length(); i++){
try {
proof.setText(response.getJSONObject(0).getString("machine_id"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
TextView proof =findViewById(R.id.proof);
proof.setText(error.getMessage());
}
}){
protected Map<String,String> getParams(){
Map<String,String > params = new HashMap<>();
params.put("username",username);
params.put("password",password);
return params;
}
};
RQ.add(array_request);
}
the username and password were already used to log in and sent as extras to this activity.
in the end it turned out that the code isn't passing through the getParams() so i turned it to a string request and parsed the response string into a jsonArray.
i couldn't find much information about it online so IDK why all this isn't working and i cant consider this an answer so it's more of an update.
I have made an android app with PHP back-end that works right on the localhost.
but, when I upload it on a server returns an empty string instead of for example "ok". I have put all the permission to 777 but it doesn't work.
one of the PHP script :
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$username = $_POST['username'];
$password = $_POST['password'];
require_once('dbConnect.php');
$sql = "SELECT * FROM coachtbl WHERE kodemelli =
'$username'
AND password='$password'";
$r = #mysqli_query($con,$sql);
$num_rows = mysqli_num_rows($r);
if($num_rows>0){
echo ("ok");}
else{
echo (mysqli_error($con));
}
#mysqli_close($con);
}
?>
And this is my android code :
StringRequest request = new StringRequest(Request.Method.POST, Config.login_Api, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
loading.dismiss();
Toast.makeText(LoginActivity.this, s, Toast.LENGTH_SHORT).show();
if (s.trim().equals("ok")) {
//Toast.makeText(LoginActivity.this, "success", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginActivity.this , MainPage.class));
kodemelli=kode.getText().toString().trim();
} else {
Toast.makeText(LoginActivity.this, "username or password is wrong", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(LoginActivity.this, volleyError.toString(), Toast.LENGTH_SHORT).show();
loading.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("username", kode.getText().toString().trim());
params.put("password", pass.getText().toString().trim());
return params;
}
};
RequestQueue requestQueue =
Volley.newRequestQueue(LoginActivity.this);
requestQueue.add(request);
Thanks for any help
Maybe Your URL Config.login_Api settings are wrong. Check for '/' backslashes missing at the end of URL: like 'www.hello.com/'
Another possible issue is that your PHP webserver is misconfigured.
Check for .htaccess settings or missing PHP Deamon running on the remote Webserver.
Replace POST by GET
You are executing a wrong HTTP method request.
I'm trying to make a POST request to an api that I have created in Visual Studio. The api works, and I finally managed to find some code that allows me to connect to it (and it's not deprecated). The problem is that this code was made for a GET request while I need to make a POST. I created two boxes where I insert the data I want to pass (utente, password) and I created a button that takes the data from the boxex and convert them to string.
I tried already searching a lot of examples and tutorials that show how to make a POST request but the majority are very old and doesn't work anymore in Android Studio, or at least I can't make them work.
Now, this is the function that should be sending the data, I haven't touched the code since I don't really know what to modify except for the Request Method.
private StringRequest searchNameStringRequest(String utente, String password)
{
String url = "http://192.168.1.11:57279/api/utente";
return new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try
{
JSONObject result = new JSONObject(response).getJSONObject("list");
int maxItems = result.getInt("end");
JSONArray resultList = result.getJSONArray("item");
}
catch (JSONException e)
{
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(MainActivity.this, "Food source is not responding (USDA API)", Toast.LENGTH_LONG).show();
}
});
}
Can someone explain me how to take the data and send it like a JSON Object that has
keys = user, password
values = utente, password (the values are from the two boxes mentioned before)
Thank to anyone who is willing to help me and I hope that asking for so much help isn't against the site rules.
I'm using Volley since is not so complicated and because it seems to work.
Using the GET method it show me the existing json with message cannot be converted to JSON object (I don't care about that, it's just a confirmation that it connects to the api)
Using the POST method it throws the ErrorResponse at the end (Food source is not responding)
EDIT: Added OnCreate method since I need a StringRequest return
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queue = Volley.newRequestQueue(this);
Button invia = findViewById(R.id.submit);
final EditText utenteInserito = findViewById(R.id.utente);
final EditText passwordInserito = findViewById(R.id.password);
invia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String utente = utenteInserito.getText().toString();
String password = passwordInserito.getText().toString();
queue.cancelAll(R.id.submit);
StringRequest stringRequest = searchNameStringRequest(utente, password);
stringRequest.setTag(R.id.submit);
queue.add(stringRequest);
}
});
}
EDIT: I have followed the suggested answer given but it doesn't seem to work
The resulting code is shown below but I get the OnErrorResponse, I don't think it's a problem with the api because trying with a GET response it gives me the exiting json array, so I think it's a problem with the code.
private StringRequest searchNameStringRequest(final String utente, final String password)
{
String url = "http://192.168.1.11:57279/api/utente";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
System.out.println(response);
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(MainActivity.this,"Service Unavailable",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String,String> map = new HashMap<>();
map.put("user", utente.trim());
map.put("password",password.trim());
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(request);
return request;
}
It's working following this question:
How to send a POST request using volley with string body?
Thanks to you all for your interest.
String url = "your url";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response);
dialog.dismiss();
try {
// your logic when API sends your some data
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(context,"Service Unavailable",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}){
//This is how you will send the data to API
#Override
protected Map<String, String> getParams(){
Map<String,String> map = new HashMap<>();
map.put("name",username.getText().toString());
map.put("password",password.getText().toString());
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(request);
}
Here is a nice tutorial, I have tried it and it worked seamlessly.
Android Login and Registration with PHP, MySQL and SQLite
You can skip the sqlite and the phpMyAdmin part.
I am searching my database for music, i have done the same in swift ios without any trouble. However when i try the same in java i am just getting my complete table and not just the tracks i am searching for. I am pretty new to android studio and java. I m using volley and i can't find the problem. seems things are not getting posted correctly or received corrected by php. Thing that really has me puzzled is that when i try to query the database in the browser i am also getting a faulty out put. When i try to do this from the ios app i'm getting the correct out put and it has searched the database correctly.
This is my android code
private void searchsong() {
String submitUrl = SEARCH_SONG_URL+"?searchWord="+searchWord;
Log.d("search song Json url", submitUrl);
JsonArrayRequest req2 = new JsonArrayRequest(Request.Method.POST, submitUrl,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// update the data in your custom method.
mJSONAdapter.updateData(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
Log.d("Submitting searchword", searchWord);
params.put("searchWord", searchWord);
Log.v("Params", "" + params);
return params;
}
};
// Adding request to request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(req2);
}
The following is the php code i am using. It is very easy. Also it is not working when i wrap in a S_post tag
<?php
header('Content-type: application/json');
//if($_POST) {
$searchWord = $_POST['searchWord'];
//open connection to mysql db
$connection = mysqli_connect("$host","$db_user","$db_password","$db_name") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = 'SELECT * FROM tracks WHERE track_name LIKE "' . $searchWord . '%"' . 'OR artist LIKE "% ' . $searchWord . '%"'. 'OR tags LIKE "% ' . $searchWord . '%"';
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($connection);
//}/*end if POST*/
?>
It seems like my android code is not posting to the php file, but when i look at the logcat it shows a url that says php?searchWord=..... i am totally lost as to what i am doing wrong. I've build a login script that check the user credentials and it works just fine. I am puzzled about why this isn't working.
Thank for your help
you don't send post params as you expect them. 2 solutions:
1) Change the request to GET
here
JsonArrayRequest req2 = new JsonArrayRequest(Request.Method.POST,
submitUrl,
and here
$searchWord = $_POST['searchWord'];
and you can remove this:
> #Override
> protected Map<String, String> getParams() {
> Map<String, String> params = new HashMap<String, String>();
>
> Log.d("Submitting searchword", searchWord);
>
> params.put("searchWord", searchWord);
>
> Log.v("Params", "" + params);
>
> return params;
>
>
> }
Option 2: Use POST but send as application/x-www-form-urlencoded
override this in your request:
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=" + getParamsEncoding();
}
/**
* Returns the raw POST or PUT body to be sent.
*
* <p>By default, the body consists of the request parameters in
* application/x-www-form-urlencoded format. When overriding this method, consider overriding
* {#link #getBodyContentType()} as well to match the new body format.
*
* #throws AuthFailureError in the event of auth failure
*/
public byte[] getBody() throws AuthFailureError {
Map<String, String> params = getParams();
if (params != null && params.size() > 0) {
return encodeParameters(params, getParamsEncoding());
}
return null;
}
/**
* Converts <code>params</code> into an application/x-www-form-urlencoded encoded string.
*/
private byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
StringBuilder encodedParams = new StringBuilder();
try {
for (Map.Entry<String, String> entry : params.entrySet()) {
encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
encodedParams.append('=');
encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
encodedParams.append('&');
}
return encodedParams.toString().getBytes(paramsEncoding);
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
}
}
I am trying to follow a online tutorial to create this login, but I receive this error. I tried this on localhost but it doesn't work on a server. Can anybody tell me what is my mistake please. Here's my code:
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
It means either the response is not in JSON format or the client side did not get any response at all. Try to following steps.:-
1.Before using the URL in the application check it in a web browser if you are getting the desired response or not. If there is any server side error it will be displayed in the web browser.
2. Now check the serve side response with a JSON validator to check if the response is a valid JSON or not
3.If your server side is then use logcat or toast message to print your response and check the response.
I just found out the way to solve it. It's the codes in the DB_Functions.php file that caused the problem. I have changed the code a bit then it works now. Thanks so much you guys for the help.I have also attached the code in case someone ran into the same problem. Good luck guys
public function getUserByEmailAndPassword($email, $password) {
$result = mysqli_query($this->conn,"SELECT * FROM users WHERE email = '$email'") or die(mysqli_connect_errno());
// check for result
$no_of_rows = mysqli_num_rows($result);
if ($no_of_rows > 0) {
$result = mysqli_fetch_array($result);
$salt = $result['salt'];
$encrypted_password = $result['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);