Catch jsonobject request sent using android volley inside servlet - json

I m trying to send json object post request to the server using android volley library.
Here is android side code :
ArrayList<CartItem> jsonSendArray = cartDetails.getShoppingList();
JsonArray array = new Gson().toJsonTree(jsonSendArray, new TypeToken<ArrayList<CartItem>>() {
}.getType()).getAsJsonArray();
JsonObject jsonObject = new JsonObject();
jsonObject.add("cartList", array);
Log.i("json_object", new JSONObject(jsonObject.toString()).toString());//this gives me the out-put in log cat {"cartList":[{"size":"M","product_id":1,"qnty":2},{"size":"S","product_id":4,"qnty":1}]}
String url = "http://10.0.2.2:8080/ECommerceApp/getAllProductsAction";
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, url,
new JSONObject(jsonObject.toString()),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.i("response", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Volley_error", error.toString());
}
});
requestQueue.add(arrayRequest);
And my server side code :
if (request.getParameter("cartList") != null) {
String jsonList = request.getParameter("cartList");
Type type = new TypeToken<List<CartItem>>() {
}.getType();
List<CartItem> conList = new Gson().fromJson(jsonList, type);
List<ProductHasSize> myList = getCompleteProductCart(conList, s);
String element = new Gson().toJson(myList, new TypeToken<List<ProductHasSize>>() {
}.getType());
response.getWriter().write(element);
} else {
JsonArray array = new JsonArray();
JsonObject jo = new JsonObject();
jo.add("error", new JsonPrimitive("Error response"));
array.add(jo);
String element = new Gson().toJson(array);
response.getWriter().write(element);
}
But what I get as the response in android side is :
I/response: [{"error":"Error response"}]
Which means executing else block of the servlet.And also proves request.getParameter("cartList") is null. Is there anything I have missed in android volley request ?? Any help would be grateful. Thank you.
UPDATE :
Overriding the getParams() method also give me the same result.
final String jsonString = new Gson().toJson(jsonSendArray, new TypeToken<ArrayList<CartItem>>() {
}.getType());
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.i("response", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Volley_error", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("cartList", jsonString);
return params;
}
};

Dont know this would be a good approach or not. But I managed to work it out like below :
In my android side :
I did override the getHeaders() method
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.i("response",response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Volley_error", error.getMessage());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/json");
params.put("cartList", jsonString);
return params;
}
};
In my Servlet :
I used getHeader("") method instead of using getParameter("")
if (request.getHeader("cartList") != null) {
String jsonList = request.getHeader("cartList");
Type type = new TypeToken<List<CartItem>>() {
}.getType();
List<CartItem> conList = new Gson().fromJson(jsonList, type);
List<ProductHasSize> myList = getCompleteProductCart(conList, s);
String element = new Gson().toJson(myList, new TypeToken<List<ProductHasSize>>() {
}.getType());
response.getWriter().write(element);
}
It works fine now . I can get the JSONArray response inside Volley.

I had the same issue, and it's mainly because on the server side, request.getParameter("cartList") would work with Content-Type="application/x-www-form-urlencoded" and not Content-Type="application/json".
The solution is to use the request.getReader() method and read the JSON string that was sent from the Android client in the POST body of the request.
BufferedReader bReader = request.getReader();
String line;
String jsonList = "";
if((line = bReader.readLine()) != null)
jsonList += line;
This is where I got the answer from: https://stackoverflow.com/a/3831791/4938794

Related

I have a problem to use Volley. want to use POST method with some parameters and get Array type response but my response is not array type

I have a problem using Volley. want to use POST method with some parameters and get Array type response but my response is not an array type. Here, I share my request code and response.
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest postRequest = new StringRequest(Request.Method.POST, "https://umrahtech.com/umrahtechapi.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
route = null;
route_spinner.setSelection(0);
check_in_date = null;
check_out_date = null;
adults = child = room = child1 = child2 = child3 = child4 = child5 = 0;
text_adults.setText("0 Adult");
text_child.setText("0 Child");
text_room.setText("0 Room");
layout_child.setVisibility(View.GONE);
in_date.setText("Add Date");
out_date.setText("Add Date");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("case", "hotel_makkah");
params.put("location", route);
params.put("check_in_1", check_in_date);
params.put("check_out_1", check_out_date);
params.put("passengers", room_array.toString());
return params;
}
};
queue.add(postRequest);
when u use string request response you get will be string also.
you should turn that response to JsonArray , then get bojects from that JsonArray something like this :
if (response != null) {
JSONArray fetchlist = JSONArray(response);
for (int i=0 ; i<fetchlist .lenght ; i++) {
JSONObject obj = fetchlist.getJSONObject(i);
Int idd = obj.getInt("genderid");
I have solved this question in this way. Where hudx_Object and hudx_JSON is JSONObject
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest hudxconnect = new StringRequest(Request.Method.POST, "https://umrahtech.com/umrahtechapi.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
hudx_Object = new JSONObject(response);
if (hudx_Object != null) {
hudx_JSON = hudx_Object.getJSONObject("response");
hudx_Object = new JSONObject(hudx_JSON.toString());
} else {
hudx_Object = null;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
progressDialog.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("case", "hotel_makkah");
params.put("location", route);
params.put("check_in_1", check_in_date);
params.put("check_out_1", check_out_date);
params.put("passengers", room_array.toString());
return params;
}
};

When i'm using volley in android studio how to get response and iterate over Json ? if it is multi-dimensional array

I can't use JsonObjectRequest instead of StringRequest because I need send it via POST method
After analyzing lot of solutions I posted the question here
My php api output is looks like
[
{
"username": "arun",
"password": "kumar"
},
{
"username": "arun",
"password": "ak"
},
{
"username": "arun",
"password": "mypass"
},
{
"username": "arun",
"password": "TestPW"
}
]
In Android side I am using below code to fetch data from web, in the method
public void onresponse()
I don't know how to get above json response, and also iterate over response to print all data in response
String url = "http://myipaddress/index.php";
StringRequest request = new StringRequest(Request.Method.POST, url, new response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonobject = new JSONObject(response);
String output = "";
for (int i = 0; i < jsonobject.length(); i++) {
// print all usernames and passwords
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, 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("username", username);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
You would need to iterate over the JSONArray and get every element as a JSONObject then get the String properties named "username" and "password" from each of them.
try this:
String url = "http://myipaddress/index.php";
StringRequest request = new StringRequest(Request.Method.POST, url, new response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
final String username = object.getString("username");
final String password = object.getString("password");
// print the output
Log.d("TAG", "username=" + username + ", password=" + password);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, 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("username", username);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
Ideally you should use class models instead, and deserialize directly into this class.
public class UserLoginInfo {
public String username;
public String password;
}
This will make the object much more easy to use and give you the benefits of type safety and autocomplete.
This is a link from a short google search on how to do it with Google's gson library.
IMO use retrofit.
Happy coding! :)

How to handle string response from php using android volley JsonObjectRequest [com.android.volley.ParseError: org.json.JSONException]?

Actually when we call API and send request in JSON format we are expecting response also come into JSON format. But here back end team sending me response in String format therefore my onErrorResponse () method get called. Here my status code is 200. But due to format of response not executed onResponse () method. So will you please help me to handle this? Might be I have to use CustomRequest here. Any suggestoin will be appreciated. Thanks
I have used volley json object request for accessing server.
My Request format is:
JSONObject json1 = new JSONObject();
try{
json1.put("","");
}catch(JSONException e){
e.printStackTrace();
}
new SampleJsonObjTask(MainActivity.this, json1);
and my SampleJsonObjTask class is:
public class SampleJsonObjTask {
public static ProgressDialog progress;
private static RequestQueue queue;
JSONObject main;
JsonObjectRequest req;
private MainActivity context;
public SampleJsonObjTask(MainActivity context, JSONObject main) {
progress = new ProgressDialog(context);
progress.setMessage("Loading...");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
progress.show();
this.context = context;
this.main = main;
ResponseTask();
}
private void ResponseTask() {
if (queue == null) {
queue = Volley.newRequestQueue(context);
}
req = new JsonObjectRequest(Request.Method.POST, "", main,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progress.dismiss();
Log.e("response","response--->"+response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", "error--->" + error.toString());
NetworkResponse response = error.networkResponse;
Log.e("statusCode","statusCode--->"+response.statusCode);
String json = null;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 400:
break;
case 401:
json = new String(response.data);
break;
case 502:
json = new String(response.data);
break;
case 200:
json = new String(response.data);
break;
}
progress.dismiss();
}
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
};
req.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, 1f));
queue.add(req);
}}
Here the Response coming like string format that is Value OK, please help me to how to get the string response which i have mentioned below.
com.android.volley.ParseError: org.json.JSONException: Value OK of type java.lang.String cannot be converted to JSONObject
How to get this string response by using json object request.
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
dialog.cancel();
Log.d("response", response);
}catch (Exception e){
volleyResponseCallBack.onFailure("Something went wrong!");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
String message = null;
dialog.cancel();
if (volleyError instanceof NetworkError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (volleyError instanceof ServerError) {
message = "The server could not be found. Please try again after some time!!";
} else if (volleyError instanceof AuthFailureError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (volleyError instanceof ParseError) {
message = "Parsing error! Please try again after some time!!";
} else if (volleyError instanceof NoConnectionError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (volleyError instanceof TimeoutError) {
message = "Connection TimeOut! Please check your internet connection.";
}
if (!(message == null)) {
Log.d("response", message);
}
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);

json parsing using uri for listview in android

ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://jsonplaceholder.typicode.com/posts";
//JSON Node Names
// private static final String TAG_OS = "Employee";
private static final String TAG_USER= "userId";
private static final String TAG_NAME = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_BODY = "body";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.user);
name = (TextView)findViewById(R.id.id);
api = (TextView)findViewById(R.id.titile);
body =(TextView)findViewById(R.id.body);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray("");
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_USER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_TITLE);
String body =c.getString(TAG_BODY);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_USER, ver);
map.put(TAG_NAME, name);
map.put(TAG_TITLE, api);
map.put(TAG_BODY, body);
list.add(map);
List=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, list,
R.layout.list_v,
new String[] { TAG_USER,TAG_NAME, TAG_TITLE,TAG_BODY }, new int[] {
R.id.user,R.id.id, R.id.titile,R.id.body});
List.setAdapter(adapter);
List.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+list.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
json parse:-
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Logcat here
java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArrayorg.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
at com.example.mind.sqlitedatabase.MainActivity$JSONParse.onPostExecute(MainActivity.java:134)
at com.example.mind.sqlitedatabase.MainActivity$JSONParse.onPostExecute(MainActivity.java:103)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Actually, I faced problem when I click get button to call uri for json parsing.
But when in android device json = null parsing...
Here I used Volley library, it handle the all the things which you did manually(Asynctask, httprequest for json).
I hope it may helps you
// JsonObject request
public void getJSONFromUrl(String url) {
RequestQueue queue = Volley.newRequestQueue(getActivity());
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response", "Response" + response);
//handle the json response
handleResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error", "Error: " + error.getMessage());
}
});
queue.add(jsonObjReq);
}
// converting from json to Map using JsonHelper class
public void handleResponse(JSONObject response) {
Map<String, Object> map = new HashMap<>();
if(response != null){
try {
// JsonObject to Map
map = JsonHelper.toMap(response);
// boolean isSuccess = map.get("success")
// if(isSuccess){
//}
if (map.size() != 0){
// use the data
}
Log.d("MAp","map" + map);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
here below class will help converting json response to MAP, from map to json.
copied from https://gist.github.com/codebutler/2339666
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
public class JsonHelper {
public static Object toJSON(Object object) throws JSONException {
if (object instanceof Map) {
JSONObject json = new JSONObject();
Map map = (Map) object;
for (Object key : map.keySet()) {
json.put(key.toString(), toJSON(map.get(key)));
}
return json;
} else if (object instanceof Iterable) {
JSONArray json = new JSONArray();
for (Object value : ((Iterable)object)) {
json.put(value);
}
return json;
} else {
return object;
}
}
public static boolean isEmptyObject(JSONObject object) {
return object.names() == null;
}
public static Map<String, Object> getMap(JSONObject object, String key) throws JSONException {
return toMap(object.getJSONObject(key));
}
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap();
Iterator keys = object.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
map.put(key, fromJson(object.get(key)));
}
return map;
}
public static List toList(JSONArray array) throws JSONException {
List list = new ArrayList();
for (int i = 0; i < array.length(); i++) {
list.add(fromJson(array.get(i)));
}
return list;
}
private static Object fromJson(Object json) throws JSONException {
if (json == JSONObject.NULL) {
return null;
} else if (json instanceof JSONObject) {
return toMap((JSONObject) json);
} else if (json instanceof JSONArray) {
return toList((JSONArray) json);
} else {
return json;
}
}
}
volley library usage
http://www.androidhive.info/2014/09/android-json-parsing-using-volley/

Google Volley not able to get JSON values from passing parameters

I am trying to pass a parameter which is the userID and then get the response in the form of the JSON.
So if userID=1 then the response would be
[{"carname":"Honda","carmodel":"Civic"}]
and if userID=5then the response would be
[{"carname":"Honda","carmodel":"Civic"},{"carname":"VW","carmodel":"Golf"},{"carname":"Ford","carmodel":"Focus"}]
But for some reason, the parameters are not being passed and if they are then I am unable to retrieve values in JSON
This is my code below:
public void getComments(int userID){
String passURL = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
(passURL, new Response.Listener<JSONArray>(){
#Override
public void onResponse(JSONArray jsonArray) {
try {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String carName = jsonObject.getString("carname");
String carModel = jsonObject.getString("carmodel");
UserStore userStore = new UserStore(carName, carModel);
list.add(userStore);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}) {
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("userID", Integer.toString(userID));
return params;
}
};
requestQueue.add(jsonArrayRequest);
}
I suspect it something to do with the fact that I am trying to get the response from the array after passing a parameter. My php works in Postman
Using mcxiaoke library version 1.0.14 and above
JsonArrayRequest
You need to set the Method as Post in JsonArrayRequest as like below
JsonArrayRequest jsonArrReq = new JsonArrayRequest(Method.POST,
url, null,new Response.Listener<JSONArray>()
{
......
//onResponse
......
}
getParams()
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user", "Android");
return params;
}