If you are using Android Studio which you should do put this line in the gradle file
compile 'com.mcxiaoke.volley:library:1.0.15'
If you want to use the GET method you should have something like that.
private void weatherData() {
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.GET,
"URL with JSON data",
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
//Your code goes here
} catch (JSONException e) {
Log.e("TAG", e.toString());
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
But if you want to post data in the server,then you should construct a HashMap and Volley library converts those key/pair values into JSON objects before posting them in the server. Here is an example.
final HashMap<String, String> postParams = new HashMap<String, String>();
postParams.put("username", username);
postParams.put("password", password);
Response.Listener<JSONObject> listener;
Response.ErrorListener errorListener;
final JSONObject jsonObject = new JSONObject(postParams);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
"YOUR URL WITH JSON DATA",
jsonObject,
new com.android.volley.Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
try {
if (response.getString("status").equals("fail")) {
} else if (response.getString("status").equals("success")) {
} catch (JSONException e) {
Log.e("TAG", e.toString())
}
}
},
new com.android.volley.Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d("TAG", "Error: " + error.getMessage());
//pDialog.dismiss();
}
}) {
@Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
VolleySingleton.getInstance(getApplicationContext()).
addToRequestQueue(jsonObjRequest);
}