Send post request using Volley and receive in PHP
Had a lot of problems myself, try this !
public class CustomRequest extends Request<JSONObject> {
private Listener<JSONObject> listener;
private Map<String, String> params;
public CustomRequest(String url,Map<String, String> params, Listener<JSONObject> responseListener, ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = responseListener;
this.params = params;
}
public CustomRequest(int method, String url,Map<String, String> params, Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
@Override
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
return params;
};
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
@Override
protected void deliverResponse(JSONObject response) {
listener.onResponse(response);
}
PHP
$username = $_POST["username"];
$password = $_POST["password"];
echo json_encode($response);
You have to make a map, the map supports key-value type, and than you post with volley.
In php you get $variable = $_POST["key_from_map"] to retreive it's value in the $variable
Then you build up the response and json_encode it.
Here is a php example of how to query sql and post answer back as JSON
$response["devices"] = array();
while ($row = mysqli_fetch_array($result)) {
$device["id"] = $row["id"];
$device["type"] = $row["type"];
array_push($response["devices"], $device);
}
$response["success"] = true;
echo json_encode($response);
You can see here that the response type is JSONObject
public CustomRequest(int method, String url,Map<String, String> params, Listener<JSONObject> reponseListener, ErrorListener errorListener)
Look at the listener's parameter!
Send post and get request at the same time in VOLLEY
I'm sorry i just saw something in Request.Method .
I didnt change anything in this code , only i changed Request.Method.GET to Request.Method.DEPRECATED_GET_OR_POST
I just saw this method now. So its working perfectly.
I can't send POST request from android volley to php
I removed the "www" from the url and it solved my problem. This SO question POST Requests seen as GET by server helped
Unable to pass data to a POST request using Volley library - Android
You specified body format as application/json, and put through as an array(form-data), that may be affecting the result. The format should be multipart/form-data (or application/x-www-form-urlencoded, as per wiki).
Android Volley POST request: getting GET request method on server side (php)
Here is code you can use to make a POST request with the Volley library in android. Assuming you import your library as such in your application build.gradle file:
dependencies{
....
implementation 'com.android.volley:volley:1.1.0'
.....
}
The following code can be put in a method as some routine task to perform your POST request
String requestUrl = "http://myapi.com/api/postresource.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, requestUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e("Volley Result", ""+response); //the response contains the result from the server, a json string or any other object returned by your server
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace(); //log the error resulting from the request for diagnosis/debugging
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> postMap = new HashMap<>();
postMap.put("param1", "value1");
postMap.put("param2", value2);
//..... Add as many key value pairs in the map as necessary for your request
return postMap;
}
};
//make the request to your server as indicated in your request url
Volley.newRequestQueue(getContext()).add(stringRequest);
Post data using volley php
Try this code it worked for me in android app, and you have to use another url to post :
private void registerUser(){
final String username = editTextUsername.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//do stuffs with response of post
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//do stuffs with response erroe
}
}){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_PASSWORD,password);
params.put(KEY_EMAIL, email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
I'm not sure with you php code, but above android part works,
you may know that you have to,
Add internet permission :
<uses-permission android:name="android.permission.INTERNET" />
Add volley to build.gradle:
compile 'com.mcxiaoke.volley:library:1.0.19'
Thanks
Related Topics
PHP Check If File Contains a String
With "Magic Quotes" Disabled, Why Does PHP/Wordpress Continue to Auto-Escape My Post Data
Decode Gzipped Web Page Retrieved Via Curl in PHP
Session Data Lost in Chrome Only
Why Doesn't MySQL Support Millisecond/Microsecond Precision
PHP: Sort and Count Instances of Words in a Given String
Parentheses Altering Semantics of Function Call Result
What Are PHP Nested Functions For
PHP Sessions Timing Out Too Quickly
How to Implement a Callback in PHP
What Is a Front Controller and How Is It Implemented
Create Ini File, Write Values in PHP
Codeigniter: "The Filetype You Are Attempting to Upload Is Not Allowed."