I am trying to make a json request using Volley library to a php server, but for some reason the server does not receive the json object I am sending, and it responds with empty string. Here is my code
import android.content.Context;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response.Listener;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class MyVolley implements Listener, ErrorListener {
private static Context appContext;
public MyVolley(Context context) {
appContext = context;
}
public void stuff() throws JSONException {
RequestQueue queue = Volley.newRequestQueue(appContext);
JSONObject obj = new JSONObject();
obj.put("param1", "assda");
obj.put("param2", "fassfafsa");
JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST, "some url here", obj, this, this);
queue.add(stringRequest);
}
@Override
public void onResponse(Object response) {
System.out.println(response);
}
@Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
}
And when it executes, this is what the server receives
array (
'Content-Type' => 'application/json; charset=utf-8',
'User-Agent' => 'pointless info here',
'Host' => 'some host here',
'Connection' => 'Keep-Alive',
'Accept-Encoding' => 'gzip',
'Content-Length' => '107',
) array (
) array (
)
Why could that be happening?
Make sure it's not a server side error (try your service using Postman for instance).
I personally faced the same issue some time ago, changing JsonObjectRequest to StringRequest fixed my problem.
Take a look at this link : https://stackoverflow.com/a/31613565/7871886
Now I use Retrofit2 instead of Volley... Could be an option. Happy coding
Not sure what was your problem, but for the future googlers:
My problem was that I was trying to read form
$_POST
instead ofphp://input
Full code (working):
Java:
Clarification:
display
andresult
are twoTextView
objects I am using to display data on the screen, andqueue
is Volley's request queue.PHP:
Your Android Monitor should output sth. like :