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;}@Overrideprotected Map<String, String> getParams() throws com.android.volley.AuthFailureError { return params;};@Overrideprotected 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)); }}@Overrideprotected 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 $variableThen 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!
JSONObject params = new JSONObject(); try { params.put("name", "Droider"); } catch (JSONException e) { e.printStackTrace(); }JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, url, params, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, response.toString()); pDialog.hide(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); pDialog.hide(); } }) { @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 queueAppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
and in your server side:
<?php $value = json_decode(file_get_contents('php://input')); $file = 'MyName.txt'; file_put_contents($file, "The received name is {$value->name} ", FILE_APPEND | LOCK_EX); ?>
open MyName.txt
and see the result.
Here is a simple code to send post request to php script
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {private static final String REGISTER_URL = "http://simplifiedcoding.16mb.com/UserRegistration/volleyRegister.php";public static final String KEY_USERNAME = "username";public static final String KEY_PASSWORD = "password";public static final String KEY_EMAIL = "email";private EditText editTextUsername;private EditText editTextEmail;private EditText editTextPassword;private Button buttonRegister;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editTextUsername = (EditText) findViewById(R.id.editTextUsername); editTextPassword = (EditText) findViewById(R.id.editTextPassword); editTextEmail= (EditText) findViewById(R.id.editTextEmail); buttonRegister = (Button) findViewById(R.id.buttonRegister); buttonRegister.setOnClickListener(this);}private void registerUser(){ final String username = editTextUsername.getText().toString().trim(); final String password = editTextPassword.getText().toString().trim(); final String email = editTextEmail.getText().toString().trim(); StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show(); } }){ @Override protected Map<String,String> getParams(){ Map<String,String> params = new HashMap<String, String>(); params.put(KEY_USERNAME,username); params.put(KEY_PASSWORD,password); params.put(KEY_EMAIL, email); return params; } }; RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest);}@Overridepublic void onClick(View v) { if(v == buttonRegister){ registerUser(); }}}
volleyRegister.php
<?phpif($_SERVER['REQUEST_METHOD']=='POST'){ $username = $_POST['username']; $email = $_POST['email']; $password = $_POST['password']; require_once('dbConnect.php'); $sql = "INSERT INTO volley (username,password,email) VALUES ('$username','$email','$password')"; if(mysqli_query($con,$sql)){ echo "Successfully Registered"; }else{ echo "Could not register"; }}else{echo 'error'}}