Volley GET with parameters - android

I have a web service which gives data in JSON array format. Right now the data is being fetched just by passing the URL. But now I want to pass a parameter to get the JSON response. This web service has GET & POST methods.
I tried with Volley - Sending a POST request using JSONArrayRequest answer, but I couldn't implement it in my code. It would be really helpful if somebody could explain, how to achieve this in my code.
This is how my code looks like
String HTTP_SERVER_URL = "https://192.168.1.7/STUDENTWS/Default.asmx/StudentDataJson?InFacultyID=string";
public void JSON_WEB_CALL(){
//mSwipeRefreshLayout.setRefreshing(true);
jsonArrayRequest = new JsonArrayRequest(HTTP_SERVER_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataModel GetDataModel = new DataModel();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataModel.setId(json.getString("STUDENTID"));
GetDataModel.setPlateNo(json.getString("GRADE"));
GetDataModel.setPlateCode(json.getString("HOUSE"));
}
catch (JSONException e)
{
e.printStackTrace();
}
DataAdapterClassList.add(GetDataModel);
mSwipeRefreshLayout.setRefreshing(false);
}
recyclerViewadapter = new NewRecyclerViewAdapter(DataAdapterClassList, this);
recyclerView.setAdapter(recyclerViewadapter);
if (array.length()!=0) {
SHOW_ALERT(array);
sendNotification(recyclerView, array);
}
}

For get with params you should create StringRequest. For example:
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.GET, "http://headers.jsontest.com/",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("HttpClient", "success! response: " + response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("HttpClient", "error: " + error.toString());
}
})
{
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("user","YOUR USERNAME");
params.put("pass","YOUR PASSWORD");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};

// for json object
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("fullname",fullName);
jsonParams.put("email",email);
jsonParams.put("password",password);
// for json array make any list.List will be converted to jsonArray
// example-----
// ArrayList<String> jsonParams =new ArrayList();
// jsonParams.add("Test1")
// jsonParams.add("Test2")
JsonObjectRequest objectRequest=new JsonObjectRequest(Request.Method.POST, url, new JSONObject(jsonParams), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: ",error );
Toast.makeText(ActivitySignUp.this,error.getMessage(), Toast.LENGTH_LONG).show();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String,String> header=new HashMap<String, String>();
header.put("Content-Type","application/json");
return header;
}
};

If you want to pass a param to your server, then you might wanna do a POST method, else.. if you only wanted to get the data, then GET method is the best way... there's also header that you can use to pass data, but, I wouldn't recommend to use header for sending params... that's a sore eyes
Edit
//Set you method POST or GET
JsonObjectRequest(Request.Method.GET(/*here can set to POST too*/), url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
// display response
Log.d("Response", response.toString());
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", response);
}
}
);

Related

How to send json data with header using volley library

I am trying to send json data to a url in the format below.
{
“amount”:500,
“merchant_id”:”104”,
“narrative”:”John”,
“reference”:”Steven”
}
To send data to the url, one needs an authorization key as the header, I have already figured out how to set the authorization key as the header in Params, as shown below
#Override
public Map<String,String >getHeaders()throws AuthFailureError{
Map<String,String >params=new HashMap<String,String>();
params.put(“Content-Type”, “text/jsom;);
params.put(“AuthKey”, Auth);
return params;
but I do not know how to send the data in the particular format shown in the first instance to the url using params with volley. Please help, I am quite new to using Volley library .
This is the rest of code I am currently using it however does not return any response except for an invalid json error. Meaning the format sent is not corresponding to the one desired.
StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(Main9Activity.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Main9Activity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<String, String>();
params.put("amount","500");
params.put("merchant_id", "104");
params.put("narrative","John");
params.put("reference", "Steven");
return params;
}
#Override public Map<String,String>getHeaders()throws AuthFailureError{
Map<String,String>headers=new HashMap<>();
params.put("Content-Type","text/json");
params.put("Authorization",Auth);
return params;
}
};
RequestQueue requestQueue=Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
You can refer below code snipet to post data with custom header in volley.
JSONObject jsonobject = new JSONObject();
jsonobject.put("amount", "500");
jsonobject.put("merchant_id", "104");
jsonobject.put("narrative", "John");
jsonobject.put("reference", "Steven");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST,url, jsonobject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
Toast.makeText(Main9Activity.this, response.toString(), Toast.LENGTH_SHORT).show();
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(Main9Activity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
hideProgressDialog();
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String >headers=new HashMap<String,String>();
headers.put(“Content-Type”, “application/json“);
headers.put(“AuthKey”, Auth);
return headers;
}
You can send as below:
The data you want to send:
Hashmap<String, Object> data = new HashMap<>();
data.put("amount", "500");
data.put("merchant_id", "104");
data.put("narrative", "John");
data.put("reference", "Steven");
RequestQueue request = Volley.newRequestQueue(context);
JsonObjectRequest jsonobj = new JsonObjectRequest(Request.Method.POST, "your url",new JSONObject(data),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
){
};
request.add(jsonobj);

How to solve Error in json parsing using volley POST?

Hi I am using volley as JSON Parsing. I am using POST method and sending parameters in post request. I am getting following error when parsing the data, I am getting following error. I want to use volley. I have tried with JsonArrayRequest but it does not allow to send parameters as JSONObject,which I am using in my code.
org.json.JSONArray cannot be converted to JSONObject
Request is like
{
"city":"acd",
"user_id":"82",
"phone_number1":"1232131231",
"my_type":"asf"
}
Response is like
[{
"name":"dfdfd",
}]
Following is my code
private void Search_Refer() {
//initialize the progress dialog and show it
progressDialog = new ProgressDialog(SearchReferNameActivity.this);
progressDialog.setMessage("Please wait....");
progressDialog.show();
try {
JSONObject jsonBody = new JSONObject();
jsonBody.put("city", "acb");
jsonBody.put("user_id", "82");
jsonBody.put("phone_number1", "12332123231");
jsonBody.put("my_type", "asf");
JsonObjectRequest jsonOblect = new JsonObjectRequest(Request.Method.POST, Constants.BASE_URL1+"api/lab/search", jsonBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
Log.e("Search EROOR", response.toString());
try {
JSONArray itemArray=new JSONArray(response);
dataModelArrayList = new ArrayList<>();
for (int i = 0; i < itemArray.length(); i++) {
SearchModel playerModel = new SearchModel();
JSONObject dataobj = itemArray.getJSONObject(i);
//playerModel.setProduct_name(dataobj.getString("name"));
playerModel.setRadiology_store_first_name(dataobj.getString("radiology_store_first_name"));
dataModelArrayList.add(playerModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
progressDialog.dismiss();
/* Intent intent = new Intent(SearchReferNameActivity.this, SearchResult.class);
intent.putExtra("Search_result", dataModelArrayList);
startActivity(intent);*/
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Response: " + error.toString(), Toast.LENGTH_SHORT).show();
System.out.println("Search Eroor"+error.toString());
progressDialog.dismiss();
}
}){
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "Bearer "+deviceToken);
return headers;
}
};
jsonOblect.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MyApplication.getInstance().addToRequestQueue(jsonOblect,"postrequest");
} catch (JSONException e) {
e.printStackTrace();
}
// Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG).show();
}
Use JsonArrayRequest or StringRequest in place of JsonObjectRequest
JsonArrayRequest
change the following response parameter to JSONArray
Instead of new Response.Listener<JSONObject> Use new Response.Listener<JSONArray>
// JSONArray insated of JSONObject
public void onResponse(JSONArray response) {
}
Use Below code
StringRequest stringRequest = new StringRequest(Request.Method.POST, "api/lab/search", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("city", "abcd");
params.put("user_id", "82");
params.put("phone_number1", "01235467895");
params.put("my_type", "asf");
return params;
}
};

Android volley is not sending params

The code which does not work is below. See anything wrong with this code , why it is not sending parameters. I am new to Android.
private void sendParams()
{
JsonArrayRequest movieReq = new JsonArrayRequest(AppConfig.URL_Q_RECIPIES,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Recipie movie = new Recipie();
movie.setRecipieName(obj.getString("recipie_name"));
movie.setId(obj.getInt("id"));
// build the image URL here
String s = AppConfig.URL_IMAGE + obj.getInt("id") + ".jpeg";
movie.setImageURL(s);
movie.setPrimaryIngrediant(obj.getString("prim_ingr"));
movie.setUrl(obj.getString("url"));
// adding movie to movies array movie is nothing but recipie
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Filter error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hidePDialog();
}
}) {
#Override
protected Map<String, String> getParams () {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("ind_ajwain", Integer.toString(session.isAjwainChecked()));
//params.put("ind_asaftide", Integer.toString(session.isAsaftideChecked()));
params.put("rec_name", "chicken"); /// change this
params.put("ind_ginger", "0");
//params.put("password", password);
return params;
}
};
Log.d(TAG, movieReq.toString());
//movieReq.
AppController.getInstance().addToRequestQueue(movieReq);
}
I followed this link to get coding don : Source: https://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/
I have not made much changes above, only changing parameters.
For sending data to server using Volley refer below code.
Step1 : Use POST method to send data.
Create below method :
private void makeJsonSend() {
StringRequest jsonObjReq = new StringRequest(Request.Method.POST,Const.ServiceType.URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("response:forgot", response);
jsonParseResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//show error message here
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("email","email");
//pass parameter here
Log.i("request send data", params.toString());
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
//If you have header parameter then set here
return headers;
}
};
AppController.getInstance().addToRequestQueue(movieReq);
}
Step 2: Response method where you have get response of that operation.
private void jsonParseResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("status").equals("200")) {
cc.showToast(jsonObject.getString("message"));
} else {
cc.showToast(jsonObject.getString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("Forgot Error",e.toString());
}
}
You didn't pass any request method in new JsonArrayRequest. You have to pass Request.Method.POST or Request.Method.GET

Android volley post methode parameter missing

I am using android volley library to post data to back-end service. But I can't send any parameter with my request. I have done each and everything mentioned here . But none works for me. The post method that I am using is:
public static void post()
{
// Tag used to cancel the request
String tag_json_obj = "json_obj_req";
String url = "http://myUrl";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
return headers;
}
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("key", "value");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
Always the response is "parameter missing".
How could i resolve this issue?
If you're using JSONObjectRequest, you can try this.
String url = "http://myurl";
Map<String, String> params = new HashMap<String, String>();
params.put("key", value);
RequestQueue queue = Volley.newRequestQueue(getActivity());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
url, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
try {
success = jsonObject.getInt("success");
message = jsonObject.getString("message");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Activity activity = getActivity();
if (volleyError instanceof NoConnectionError) {
String errormsg = "Check your internet connection";
Toast.makeText(activity, errormsg, Toast.LENGTH_LONG).show();
}
}
});
queue.add(jsonObjectRequest);
The codes are more likely the same as yours. Check on the lines where I put the data to be posted. I'm very sure this would work!
The problem is you are approaching the request as though you were making a stringRequest. The link you reference is talking specifically about making a stringRequest.
jsonObjectRequest actually lets you put the json object into the constructor itself, instead of using the override method getParams() like so:
String url = "some_url";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put(Constants.LOGIN_EMAIL_ID, email);
jsonObject.put(Constants.LOGIN_PASSWORD, password);
}catch(JSONException e){
Log.d("JSON error", e.getMessage(), e);
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest(url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("RESPONSE", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(error.getMessage()!=null){
Log.d("RESPONSE", error.getMessage());
}
}
});
VolleySingleton.getInstance(activity).getRequestQueue().add(jsObjRequest);

Android Volley POST JsonObject and get JsonArray or JsonObject or Other response

in volley we have some ability to retrieve data from server such as jsonObject,jsonArray and String. in this below sample we can get simply jsonObject or jsonArray response from server,
public static void POST(HashMap<String, String> params, final Listeners.ServerResponseListener listener) {
JsonObjectRequest req1 = new JsonObjectRequest(ApplicationController.URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("Response:", response.toString());
if (listener != null)
listener.onResultJsonObject(response);
else
Log.e(TAG,"Error: SetServerResponse interface not set");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error: ", error.getMessage());
}
});
ApplicationController.getInstance().addToRequestQueue(req1);
}
my problem is i want to send jsonObject from this method and get jsonArray or jsonObject from server, and i can not get simply array from server with this method. for example i must be filter server response with this jsonObject:
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");
params.put("search_count", "10");
params.put("order_by", "id");
server return jsonArray and i can not get that with Volley response
Looking at the source code of JsonArrayRequest. There is a constructor which takes in a JSONObject. You should check it out
public class RetreiveData {
public static final String TAG = RetreiveData.class.getSimpleName();
public static void POST(String localhost, final HashMap<String, String> params, final Listeners.ServerResponseListener listener) {
StringRequest post = new StringRequest(Request.Method.POST, localhost, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
if (listener != null)
listener.onResponse(response.toString());
else
Log.e(TAG, "Error: SetServerResponse interface not set");
} catch (Exception e) {
e.printStackTrace();
Log.d("Error: ", e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error: ", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = params;
return map;
}
#Override
public RetryPolicy getRetryPolicy() {
setRetryPolicy(new DefaultRetryPolicy(
5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
return super.getRetryPolicy();
}
};
ApplicationController.getInstance().addToRequestQueue(post);
}
}

Categories

Resources