Android Volley not being recognized as POST on server with php - java

I am using volley to sent post to my server. in my php inside insert.php i have code like this
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//do all post functions
}
else{
//notofication that says its not post
}
This is my volley code in my android
String HttpUrl = "http://192.168.30.18/insert.php";
// 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(CreateAccountOrLoginActivity.this, ServerResponse, Toast.LENGTH_LONG).show();
Log.d("responseSuccess",ServerResponse);
}
},
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(CreateAccountOrLoginActivity.this, volleyError.toString(), Toast.LENGTH_LONG).show();
Log.d("responseFail",volleyError.toString());
}
}) {
#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("title",title);
params.put("name", fname);
params.put("surname", sname);
return params;
}
};
// Creating RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(CreateAccountOrLoginActivity.this);
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
The problem is after the android code is run, it returns what is in the else statement of the insert.php instead of what is in the if statement, meaning it is not being recognized as a post. How do i resolve it to make it run in the if statement

Related

How to set checks on different responses volley and get different responses when the request is string request

I'm sending post request for login user on server through volley string request. It works perfectly but the problem is that after sending request server returns me two responses one is success in which token id is given and the other one is failure in which unauthorized user is toast. Im getting the response perfectly but can use check to differentiate these responses. Kindly someone helps me Im very thakful to you.
I'm trying many times but can't get the exact solution.
RequestQueue queue = Volley.newRequestQueue(this);
String url =LOGIN_URL;
final StringRequest strRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", grant_type);
params.put("client_id", client_id);
params.put("client_secret", client_secret);
params.put("username", email);
params.put("password", password);
return params;
}
};
queue.add(strRequest);

Make POST request to Api in Android Studio

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.

Send Images as Multipart with Other Params in Volley Request

I was sending a request to the server with two parameters using volley request and it was working fine. Now the requirement has changed and I need to send at least one image or maximum 3 images to the server along with the other two parameters. The image must be sent as multi-part. I have following code for Getting image from gallery and storing their file paths in the list.
List<String> imagePathList = imageFilePaths;
List<MultipartBody.Part> partMap = new ArrayList<>();
for (int i = 0; i < imagePathList.size(); i++) {
Uri fileUri = Uri.parse(imagePathList.get(i));
RequestBody requestFile = RequestBody.create(
MediaType.parse(getMimeTypee(FileUtils.getFile(getContext(), fileUri).getAbsolutePath())),
FileUtils.getFile(getContext(), fileUri)
);
MultipartBody.Part body = MultipartBody.Part.createFormData("court_image[" + i + "]", FileUtils.getFile(getContext(), fileUri).getName(), requestFile);
partMap.add(body);
}
Where imageFilePaths is an ArrayList. The server will receive images like court_image[0], court_image[1] and so on, depends on how many image paths I have in ArrayList.
The volley request is here:
RequestQueue queue = Volley.newRequestQueue(getContext());
StringRequest postRequest = new StringRequest(Request.Method.POST, url1,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(mBaseAppCompatActivity, "Success", Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
String token = getToken();
params.put("Authorization", "Bearer " + token);
params.put("Content-Type", "multipart/form-data");
return params;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("terms", "true");
params.put("phone", "phoneNo");
return params;
}
};
queue.add(postRequest);
Now the thing is as I am new to the multi-part thing, with the help I am able to get the image from gallery and storing their path in ArrayList but I don't know how to pass the multi-part data in this volley request. Please help.
For uploading the image along with some other parameters, I used volley. However, I found a wrapper of the original volley library which is easier to integrate for multi-part requests. Hence I added the following library in the build.gradle file.
dependencies {
compile 'dev.dworks.libs:volleyplus:+'
}
I removed the original volley library from my build.gradle and used the above library instead which can handle both multi-part and normal requests having similar integration technique.
Then I just had to write the following class which handles the POST request operation.
public class POSTMediasTask {
public void uploadMedia(final Context context, String filePath) {
String url = getUrlForPOSTMedia(); // This is a dummy function which returns the POST url for you
SimpleMultiPartRequest multiPartRequestWithParams = new SimpleMultiPartRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
// TODO: Do something on success
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle your error here
}
});
// Add the file here
multiPartRequestWithParams.addFile("file", filePath);
// Add the params here
multiPartRequestWithParams.addStringParam("terms", "SomeTerms");
multiPartRequestWithParams.addStringParam("phone", "85050055055");
RequestQueue queue = Volley.newRequestQueue(context);
queue.add(multiPartRequestWithParams);
}
}
Now execute the task like the following.
new POSTMediasTask().uploadMedia(context, mediaPath);
You can upload one file at a time using this library. However, I could manage to upload multiple files, just by initiating multiple tasks.

What is the best way to save a RequestQueue response?

all. First time posting here.
Anyway, I wrote an Android method that creates a RequestQueue and sends a request to my server via a PHP script to get the server time. The way I have it DOES work, but I'm almost certain it's jury rigged code and there must be a better way to do it.
Bottom Line: I want to save the onResponse response into a String time that I can return (time was a String before being changed to an ArrayList). However, it won't let me use a String from outside onResponse unless it is final. Of course that means I can't change it to response.
I think I'm going about it wrong. Maybe there's a better way to get a response from the PHP script?
The Android method:
public static String getServerTime(Context c){
//Make a final ArrayList that will hold response once received
final ArrayList<String> time = new ArrayList<String>();
//Set up the RequestQueue
RequestQueue requestQueue = Volley.newRequestQueue(c);
String requestUrl = c.getString(R.string.uploadServerUrl)+c.getString(R.string.serverRequestPath);
Response.Listener responseListener = new Response.Listener<String>() { #Override public void onResponse(String response) { time.add(response.toString()); System.out.println("onResponse: "+response.toString());}};
Response.ErrorListener errorListener = new Response.ErrorListener() { #Override public void onErrorResponse(VolleyError error) {System.out.println("onErrorResponse: "+error.toString());}};
StringRequest request = new StringRequest(Request.Method.POST, requestUrl, responseListener, errorListener){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("option", "0");
return parameters;
}
};
RetryPolicy retryPolicy = new RetryPolicy(){
#Override public int getCurrentTimeout() {
return 50000;
}
#Override public int getCurrentRetryCount() {
return 50000;
}
#Override public void retry(VolleyError error) throws VolleyError {}
};
request.setRetryPolicy(retryPolicy);
requestQueue.add(request);
return time.remove(0);
}
The PHP script:
<?php
if(isset($_POST["option"])){
$option = $_POST["option"];
switch($option){
case 0:
date_default_timezone_set ("America/Chicago");
$time = time();
echo(date("Y;m;d;H;i;s", $time));
}
}
else{
echo "No option set!";
}
?>

Volley library dosent connect to server in some devices

in first i'm use Httpurlconnection and have same issue(Dosent find my Url in server in some devices and other device conncet easy) and i think bug e Httpurlconnection and i decide use Volley and same issue exist when use that
Error:
com.android.volley.VolleyError:java.lang.NullPointerException
Volley Code :
StringRequest postRequest = new StringRequest(Request.Method.POST, uri,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("HOOOO", response);
progressDialog.dismiss();
try {
JSONObject jsonobj = new JSONObject(response);
int success = Integer.parseInt(jsonobj.getString("success"));
String msg = jsonobj.getString("message");
check(Flag,success,msg,pass,email);
}catch (Exception e){
Snackbar snackbar1 = Snackbar.make(Mainlayout,e.toString(), Snackbar.LENGTH_LONG);
snackbar1.show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Log.i("Error Respone", error.toString());
Snackbar snackbar1 = Snackbar.make(Mainlayout,error.toString(), Snackbar.LENGTH_LONG);
snackbar1.show();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
if(Flag=="Insert") {
params.put("email", email);
params.put("fact", DeviseBrand);
params.put("model", DeviseModel);
}else if((Flag=="signin") ||(Flag=="update") ){
params.put("email", email);
}
// the POST parameters:
return params;
}
};
postRequest.setRetryPolicy(new DefaultRetryPolicy(
9000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(this).add(postRequest);
and my uri :
http://domain.com/App/Register.php
Post data and on server get with _Request[];
Volley is a very strong API, i don't think they could have such an issue, check your code maybe in some cases it doesn't initialize the object correctly.
I used Volley for more than 1 year and didn't had such issue.
1-check that you are using the latest release from this link.
2-put your code in question so we can check it with you, also the log could be helpful to trace the issue, also what is the device you are using ?

Categories