Jika Anda menggunakan Android Studio, Anda harus meletakkan baris ini di file gradle
compile 'com.mcxiaoke.volley:library:1.0.15'
Jika Anda ingin menggunakan metode GET, Anda harus memiliki sesuatu seperti itu.
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);
}
Tetapi jika Anda ingin memposting data di server, maka Anda harus membuat pustaka HashMap dan Volley mengonversi nilai kunci / pasangan tersebut menjadi objek JSON sebelum mempostingnya di server. Berikut ini contohnya.
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);
}