How to post JSON data using volley library? - android

I have following format of posting data to server. I want to post these data to server using volley library and following request contains multiple images' base64 content also. I am passing this as StringRequest i got the error of invalid JSON data format. How can i post following data to server? Or any other useful way to pass following data to server then also let me know. So that i can solve this problem and efficiently can upload on server.
{
"TakeoffID": "2",
"ViewPhoto1": "image base64 content",
"ViewPhoto2": "image base64 content",
"LineItems": [
{
"OrderLineid": "964",
"OrderLinePhoto1": "image base64 content",
"OrderLinePhoto2": "image base64 content"
},
{
"OrderLineid": "963",
"OrderLinePhoto1": "image base64 content",
"OrderLinePhoto2": "image base64 content"
}
]
}
===========
Following is my code to upload above data:
private void uploadImage(final CustomerBean bean,final String line_items)
{
// Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(mActivity, "Uploading...", "Please wait...", false, false);
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, Const.API_SYNC_ALL_DATA, new Response.Listener<String>() {
#Override
public void onResponse(String s)
{
loading.dismiss();
Log.print("======UPLOAD IMAGE=====", s);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError)
{
loading.dismiss();
Toast.makeText(mActivity, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String, String> params = new Hashtable<String, String>();
params.put("TakeoffID", "2");
params.put("ViewPhoto1", bean.photo1);
params.put("ViewPhoto2", bean.photo2);
params.put("LineItems", line_items);
// returning parameters
return params;
}
};
// Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(mActivity);
// Adding request to the queue
requestQueue.add(stringRequest);
}
===========================
And I am getting following error from server.
[
{
"code": "-1",
"message": "The json data format is incorrect"
}
]

You can also use following block of code for pass json object to Volley as a parameter. Just check it once.
JSONObject data= new JSONObject();
data.accumulate("username", "mobileGps");
data.accumulate("password", "9565551236");
JSONObject total= new JSONObject();
total.put("data",data);
json = jsonObjectNew.toString();

IMO, you can refer to my following sample code:
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
// Prepares POST data...
JSONObject jsonBody = new JSONObject();
jsonBody.put("TakeoffID", "2");
jsonBody.put("ViewPhoto1", "image base64 content");
jsonBody.put("ViewPhoto2", "image base64 content");
// "OrderLineid": "964"...
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("OrderLineid","964");
jsonObject1.put("OrderLinePhoto1","image base64 content");
jsonObject1.put("OrderLinePhoto2","image base64 content");
// "OrderLineid": "963"...
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("OrderLineid","963");
jsonObject2.put("OrderLinePhoto1","image base64 content");
jsonObject2.put("OrderLinePhoto2","image base64 content");
JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonObject1);
jsonArray.put(jsonObject2);
// "LineItems"...
jsonBody.put("LineItems", jsonArray);
final String mRequestBody = jsonBody.toString();
// Volley request...
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
mRequestBody, "utf-8");
return null;
}
}
};
requestQueue.add(request);
} catch (JSONException e) {
e.printStackTrace();
}
Hope it helps!

Related

How should i get the data from sourceJson in android using volley?

Below is the response what i am getting i want to get the data from "SourceJson" m not ble to understnd why i am getting "" in source json please help me
{
"incomingOrder": [
{
"Namw": 8510,
"Surname": "00",
"mob": "00",
"phone": "000",
"SourceJson": "{\"cart_gst\":30.21,\"instructions\":\"\",\"order_packing_charges\":30,\"cart_igst_percent\":0,\"cart_sgst\":15.1038,}",
"test": "NotSynced",
"test": "DPA",
}]}
Try this code :
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, JsonURL,
// The third parameter Listener overrides the method onResponse() and passes
//JSONObject as a parameter
new Response.Listener<JSONObject>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("incomingOrder");
JSONObject jsonObject = jsonArray.getJSONObject(0);
JSONObject objSourceJson=jsonObject.getJSONObject("SourceJson");
Log.i("IvaSourceJson",objSourceJson.toString());
String cart_gst=objSourceJson.getString("cart_gst");
String instructions=objSourceJson.getString("instructions");
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
},
// The final parameter overrides the method onErrorResponse() and passes VolleyError
//as a parameter
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
// Adds the JSON object request "obreq" to the request queue
requestQueue.add(obreq);
As it is JSONArray data is of list type, better not to use jsonArray.getJSONObject(0);.
Use this code for multiple results,
StringRequest request = new StringRequest(Request.Method.GET, "", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject object = new JSONObject(response);
JSONArray array = object.getJSONArray("incomingOrder");
for (int i = 0; i < array.length(); i++){
JSONObject object1 = array.getJSONObject(i);
String name = object1.getString("Namw");
String surname = object1.getString("Surname");
String mob = object1.getString("mob");
String phone = object1.getString("phone");
String sourceJson = object1.getString("SourceJson");
String test = object1.getString("test");
String test1 = object1.getString("test");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.getMessage());
}
});
Context context;
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(request);
Code this in any method and call the method where the action needed.

Android Volly Parsing Error for Nested JSONObject

I am trying to post Json data via Android Volly library but getting an error.
Here is my Json body which perfectly working with Postman.
{
"fullName": "Mr X",
"fatherName": "Mr Y",
"motherName": "Mrs Z",
"nidNo": "34345",
"surveyDate": "2020-03-25",
"birthCertificateNo": "3435355",
"mobileNumber": "01834261758",
"dateOfBirth": "",
"gender": "Male",
"bloodGroup": "A+",
"numOfDaysSick": "23",
"numOfContInftPerson": "0",
"remarks": "Need Rest",
"physicalSymptoms": ",Runny nose,Sore throat",
"status": "User",
"isForeignVisitor": "false",
"isRead": "false",
"presentAddress": {
"village": "Sonapur",
"postOffice": "Noahat",
"postCode": "1219",
"upazila": "Sonaimuri",
"district": "Noakhali",
"division": "Chittagong"
},
"permanentAddress": {
"village": "Sonapur",
"postOffice": "Noahat",
"postCode": "1234",
"upazila": "Sonaimuri",
"district": "Noakhali",
"division": "Chittagong"
}}
But when i try to send it via Android Volly's Post call I am getting the error below :
com.android.volley.ParseError: org.json.JSONException: Value Survey of type java.lang.String cannot be converted to JSONObject
Here is my Android method to generate this Json body.
Note that : I can successfully generate Json body with this Android method and copy paste(from Logcat) to Postman, it works fine. But Android Volly giving me such error. My url is also ok because I tested it manually.
public void SendSurveyDataToServer(){
customProgressBar.show();
//--
//-------------------------------
JSONObject permanent_address = new JSONObject();
try {
permanent_address.put("village", village_pS);
permanent_address.put("postOffice", post_office_pS);
permanent_address.put("postCode", post_code_pS);
permanent_address.put("upazila", upazilla_pS);
permanent_address.put("district", district_pS);
permanent_address.put("division", division_pS);
} catch (JSONException e) {
e.printStackTrace();
}
//--
JSONObject present_address = new JSONObject();
try {
present_address.put("village", village_tS);
present_address.put("postOffice", post_office_tS);
present_address.put("postCode", post_code_tS);
present_address.put("upazila", upazilla_tS);
present_address.put("district", district_tS);
present_address.put("division", division_tS);
} catch (JSONException e) {
e.printStackTrace();
}
//--
if(numberofContactedPersonS.equals("Yes")){
numberofContactedPersonS = "true";
}else{
numberofContactedPersonS = "false";
}
//--
//--
JSONObject parameters = new JSONObject();
try {
parameters.put("fullName", fullNameS);
parameters.put("fatherName", fatherNameS);
parameters.put("motherName", motherNameS);
parameters.put("nidNo", nidNoS);
parameters.put("surveyDate", "2020-03-25");
parameters.put("birthCertificateNo", birthdayCertificateNoS);
parameters.put("mobileNumber", mobileNoS);
parameters.put("dateOfBirth", "");
parameters.put("gender", gender_selectS);
parameters.put("bloodGroup", blood_group_selectS);
parameters.put("numOfDaysSick", sickDaysNoS);
parameters.put("numOfContInftPerson", "0");
parameters.put("remarks", remarksS);
parameters.put("physicalSymptoms", physicalSymptomsS);
parameters.put("status", statusS);
parameters.put("isForeignVisitor", numberofContactedPersonS );
parameters.put("isRead", "false");
parameters.put("presentAddress", present_address);
parameters.put("permanentAddress", permanent_address);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(classTag,parameters.toString());
RequestQueue rq = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST, ApiClass.server_path+ApiClass.saveSurvey, parameters, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String respo=response.toString();
Log.d(classTag,respo);
//iosDialog.cancel();
//Parse_signup_data(respo);
Log.e(classTag,respo);
if(respo.equalsIgnoreCase("Survey Info save Successfully")){
Toast.makeText(Survey.this,"Your survey submitted successfully. Thank you!",Toast.LENGTH_LONG).show();
//----------------------------------------
}else if(respo.equalsIgnoreCase("Survey Info already exits")){
Toast.makeText(Survey.this,"Survey info already exist with this NID and Birth Certificate Number!",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(Survey.this,"There is an error while submitting your survey, please try again!",Toast.LENGTH_LONG).show();
Log.e(classTag,"There is an error while submitting your survey, please try again!");
}
customProgressBar.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
// Toast.makeText(MainActivity.this,"Can't connect with server! Please check your network connection.",Toast.LENGTH_LONG).show();
customProgressBar.hide();
Log.d(classTag,error.toString());
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(30000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.getCache().clear();
rq.add(jsonObjectRequest);
//--------------
}
After searching for 3 days I found that the problem is API response. It was giving me 'Success' and 'Failed' in byte format but I was always checking the response for JSONObject or at least String. Postman converted the byte data into string automatically and showed me, for that reason I thought server was giving me the response in string format.
However, I sent the Json request by Volly's String Request and track the response. Then I found what is messing with me! Our backend developer might be lazy to give a response in String or Json format.
I got the response by converting byte to string :
String string = new String(response.data, StandardCharsets.UTF_8);
Here is my modification for this :
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = ApiClass.server_path+ApiClass.saveSurvey;
final String requestBody = parameters.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
customProgressBar.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
customProgressBar.hide();
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
//customProgressBar.hide();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
String string = new String(response.data, StandardCharsets.UTF_8);
Log.e(classTag,string);
serverMsg = string;
showServerMsgNow = true;
Log.e(classTag,"Server msg : "+serverMsg+" server show : "+showServerMsgNow);
// ShowServerResponse();
}
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);

How Can I get Multi Json Response without merge JSON In Android with node js using Volley?

I'm using Android studio with Nodejs. To get data, I want to get Json from nodejs server using 'volley' At server( Nodejs, Express) delivery Tow JSon
res.write(JSON.stringify(results));
res.write(JSON.stringify(hot));
i want to get these Jsons from server to Android but fail... i can get only one JSON which is delivered first , this one
res.write(JSON.stringify(results));
how can i get two JSON ?? without merge JSON
public void onButton1Clicked(View v){
String url=editText.getText().toString();
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
println(response);
JSONArray jarray= new JSONArray(response);
for(int i=0;i<jarray.length();i++)
{
JSONObject Jobs=jarray.getJSONObject(i);
String title=Jobs.getString("title");
String content=Jobs.getString("content");
println(" title : " + title);
println(" content : " + content);
}
} catch (Exception e) {
println("에러남!");
e.printStackTrace();
}
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
println("error!###");
error.printStackTrace();
}
}
){
#Override
protected Map<String, String> getParams(){
Map<String, String> params = new HashMap<>();
return params;
}
};
request.setShouldCache(false);
Volley.newRequestQueue(this).add(request);
println("웹 서버에 요청함 : "+url);
}

Android Json Arraylist to Server with Restful Web service

This is my Arraylist which I get from the previous fragment,
listoftags = getArguments().getParcelableArrayList("data");
It works well. Now I have to send this with some parameters like below:
public void volleyJsonObjectRequest(final String SessionID , final String CustomerID, final String ServiceState , final String ServiceID, final String Address, final String PaymentMode, final String CustomerComments , final ArrayList Items){
String REQUEST_TAG = "volleyJsonObjectRequest";
// POST parameters
CustomRequest request = new CustomRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Toast.makeText(SignActivity.this, response.toString(), Toast.LENGTH_SHORT).show();
Log.d("response",""+response.toString());
/* String status = response.optString("StatusMessage");
String actionstatus = response.optString("ActionStatus");
Toast.makeText(getActivity(), ""+status, Toast.LENGTH_SHORT).show();
if(actionstatus.equals("Success"))
{
// Intent i = new Intent(SignActivity.this, LoginActivity.class);
// startActivity(i);
// finish();
}*/
dismissProgress();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error."+error.toString(), Toast.LENGTH_SHORT).show();
Log.d("response",""+error.toString());
dismissProgress();
}
}) {
/* #Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}*/
public String getBodyContentType()
{
return "application/json; charset=utf-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
JSONArray jsArray = new JSONArray(listoftags);
params.put("SessionID", SessionID);
params.put("CustomerID", CustomerID);
params.put("ServiceState", ServiceState);
params.put("ServiceID", ServiceID);
params.put("Address", Address);
params.put("PaymentMode",PaymentMode);
params.put("CustomerComments",CustomerComments);
params.put("Items",jsArray.toString());
return params;
}
};
AppSingleton.getInstance(getActivity().getApplicationContext())
.addToRequestQueue(request, REQUEST_TAG);
}
but it getting error to me I want to send it like
// server side //
{
"SessionID":"9lm5255sg0ti9",
"CustomerID":"9",
"ServiceState":"Karnataka",
"ServiceID":"3",
"Address":"sfaff",
"PaymentMode":"cash",
"CustomerComments":"this is fine",
"Items":[
{
"ItemId":1,
"Cost":6777,
"Quantity":33333
}
]
}
How can send arraylist, with other strings, as raw data using volley on server.
JsonObjectRequest can be used to execute rest api using json as input.
JsonObject jobj = new JsonObject();
jobj.put("key","value");
jobj.put("key","value");
jobj.put("key","value");
jobj.put("key","value");
JsonObjectRequest request = new JsonObjectRequest(requestURL, jobj, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
}
});
*Now add this request in request queue of volley.*
Here jobj is containing input parameters. It can contain even json array inside a JsonObject. Let me know in case of any query.
Rather then volley try retrofit. Make pojo model of your object you want to send, you can make that from pojo classes from https://www.jsonschema2pojo.org the send the whole object on restapi
// try the request //
try {
REQUEST QUEUE
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
String URL = url;
JSONObject jsonBody = new JSONObject();
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
Iterator itr = listoftags.iterator();
while(itr.hasNext()){
AddRowItem ad=(AddRowItem)itr.next();
jsonObject.put("ItemId:",1);
jsonObject.put("Cost:",ad.getPrices());
jsonObject.put("Quantity:",ad.getQty());
// Log.d("ItemId:",""+1+" "+"Cost:"+ad.getPrices()+" "+"Quantity:"+ad.getQty());
}
jsonArray.put(jsonObject);
JSON VALUES PUT
jsonBody.put("SessionID", "9kp0851kh6mk3");
jsonBody.put("CustomerID", "9");
jsonBody.put("ServiceState", "Karnataka");
jsonBody.put("ServiceID", "3");
jsonBody.put("Address", "Address Demo");
jsonBody.put("PaymentMode", "cost");
jsonBody.put("CustomerComments", "Android Volley Demo");
jsonBody.put("Items", jsonArray);
final String requestBody = jsonBody.toString();
Log.d("string ---- >",""+requestBody);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
showToast("get value"+response.toString());
try {
JSONObject jObj = new JSONObject(response);
String action = jObj.get("ActionStatus").toString();
String status = jObj.getString("StatusMessage");
{"ActionStatus":"Success","StatusMessage":"Order Created","RefIDName":"OrderID","RefIDValue":19}
showToast("get value"+action);
}
catch (JSONException e)
{
showToast("get error"+e.toString());
Log.d("errorissue",""+e.toString());
}
dismissProgress();
}
}, new Response.ErrorListener() {
// error response //
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
showToast("get error"+error.toString());
dismissProgress();
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
dismissProgress();
}
}
}
// THIS IS THE WAY ISSUE RESLOVED //
THANKS EVERYONE ...

Volley JsonObjectRequest Post parameters no longer work

I am trying to send POST parameters in a Volley JsonObjectRequest. Initially, it was working for me by following what the official code says to do of passing a JSONObject containing the parameters in the constructor of the JsonObjectRequest. Then all of a sudden it stopped working and I haven't made any changes to the code that was previously working. The server no longer recognizes that any POST parameters are being sent. Here is my code:
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://myserveraddress";
// POST parameters
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "test");
JSONObject jsonObj = new JSONObject(params);
// Request a json response from the provided URL
JsonObjectRequest jsonObjRequest = new JsonObjectRequest
(Request.Method.POST, url, jsonObj, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
});
// Add the request to the RequestQueue.
queue.add(jsonObjRequest);
Here is the simple tester PHP code on the server:
$response = array("tag" => $_POST["tag"]);
echo json_encode($response);
The response I get is {"tag":null}
Yesterday, it worked fine and was responding with {"tag":"test"}
I haven't changed a single thing, but today it is no longer working.
In the Volley source code constructor javadoc it says that you can pass a JSONObject in the constructor to send post parameters at "#param jsonRequest":
https://android.googlesource.com/platform/frameworks/volley/+/master/src/main/java/com/android/volley/toolbox/JsonObjectRequest.java
/**
* Creates a new request.
* #param method the HTTP method to use
* #param url URL to fetch the JSON from
* #param jsonRequest A {#link JSONObject} to post with the request. Null is allowed and
* indicates no parameters will be posted along with request.
I have read other posts with similar questions, but the solutions haven't worked for me:
Volley JsonObjectRequest Post request not working
Volley Post JsonObjectRequest ignoring parameters while using getHeader and getParams
Volley not sending a post request with parameters.
I've tried setting the JSONObject in the JsonObjectRequest constructor to null, then overriding and setting the parameters in the "getParams()", "getBody()", and "getPostParams()" methods, but none of those overrides has worked for me. Another suggestion was to use an additional helper class that basically creates a custom request, but that fix is a bit too complex for my needs. If it comes down to it I will do anything to make it work, but I am hoping that there is a simple reason as to why my code was working, and then just stopped, and also a simple solution.
You just have to make a JSONObject from your HashMap of parameters:
String url = "https://www.youraddress.com/";
Map<String, String> params = new HashMap();
params.put("first_param", 1);
params.put("second_param", 2);
JSONObject parameters = new JSONObject(params);
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, parameters, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//TODO: handle success
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
//TODO: handle failure
}
});
Volley.newRequestQueue(this).add(jsonRequest);
I ended up using Volley's StringRequest instead, because I was using too much valuable time trying to make JsonObjectRequest work.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://myserveraddress";
StringRequest strRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "test");
return params;
}
};
queue.add(strRequest);
This worked for me. Its just as simple as JsonObjectRequest, but uses a String instead.
I had a similar problem, but I found out that the problem was not on the client side, but in the server side. When you send a JsonObject, you need to get the POST object like this (in the server side):
In PHP:
$json = json_decode(file_get_contents('php://input'), true);
You can use StringRequest to do the same things you can wtih JsonObjectRequest, while still beeing able to easily send POST parameters. The only thing you have to do is to create a JsonObject out of the request String you get, and from there you can continue as if it were JsonObjectRequest.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//Creating JsonObject from response String
JSONObject jsonObject= new JSONObject(response.toString());
//extracting json array from response string
JSONArray jsonArray = jsonObject.getJSONArray("arrname");
JSONObject jsonRow = jsonArray.getJSONObject(0);
//get value from jsonRow
String resultStr = jsonRow.getString("result");
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String,String>();
parameters.put("parameter",param);
return parameters;
}
};
requestQueue.add(stringRequest);
Use CustomJsonObjectRequest helper class mentioned here.
and implement like this -
CustomJsonObjectRequest request = new CustomJsonObjectRequest(Method.POST, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error.", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("id", id);
params.put("password", password);
return params;
}
};
VolleySingleton.getInstance().addToRequestQueue(request);
Using the JSONObject object to send parameters means the parameters will be in JSON format in the HTTP POST request body :
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "test");
params.put("tag2", "test2");
JSONObject jsonObj = new JSONObject(params);
Will create this JSON object and insert it into the body of the HTTP POST request:
{"tag":"test","tag2":"test2"}
Then the server must decode the JSON to understand these POST parameters.
But normally HTTP POST paramaters are write in the body like:
tag=test&tag2=test2
But NOW here the question is why Volley is set in this manner?
A server reading a HTTP POST method should by standard always try to read parameters also in JSON (other than in plain text) and so a server that does not accomplish is a bad server?
Or instead a HTTP POST body with parameters in JSON is not what normally a server want?
Might help someone and save you some time thinking.
I had a similar issue, the server code was looking for the Content-Type header. It was doing it this way:
if($request->headers->content_type == 'application/json' ){ //Parse JSON... }
But Volley was sending the header like this:
'application/json; charset?utf-8'
Changing the server code to this did the trick:
if( strpos($request->headers->content_type, 'application/json') ){ //Parse JSON...
I had similar problem. But I found out that the problem was not on the server side, but the problem is about cache. You have to clear your RequestQueue Cache.
RequestQueue requestQueue1 = Volley.newRequestQueue(context);
requestQueue1.getCache().clear();
You can do it this way:
CustomRequest request = new CustomRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Toast.makeText(SignActivity.this, response.toString(), Toast.LENGTH_SHORT).show();
Log.d("response",""+response.toString());
String status = response.optString("StatusMessage");
String actionstatus = response.optString("ActionStatus");
Toast.makeText(SignActivity.this, ""+status, Toast.LENGTH_SHORT).show();
if(actionstatus.equals("Success"))
{
Intent i = new Intent(SignActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
dismissProgress();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SignActivity.this, "Error."+error.toString(), Toast.LENGTH_SHORT).show();
Log.d("response",""+error.toString());
dismissProgress();
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Email", emailval);
params.put("PassWord", passwordval);
params.put("FirstName", firstnameval);
params.put("LastName", lastnameval);
params.put("Phone", phoneval);
return params;
}
};
AppSingleton.getInstance(SignActivity.this.getApplicationContext()).addToRequestQueue(request, REQUEST_TAG);
as per CustomRequest below link
Volley JsonObjectRequest Post request not working
It does work.
I parsed json object response using this:-
works like a charm.
String tag_string_req = "string_req";
Map<String, String> params = new HashMap<String, String>();
params.put("user_id","CMD0005");
JSONObject jsonObj = new JSONObject(params);
String url="" //your link
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, jsonObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("responce", response.toString());
try {
// Parsing json object response
// response will be a json object
String userbalance = response.getString("userbalance");
Log.d("userbalance",userbalance);
String walletbalance = response.getString("walletbalance");
Log.d("walletbalance",walletbalance);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
AppControllerVolley.getInstance().addToRequestQueue(jsonObjReq, tag_string_req);
It worked for me can try this for calling with Volley for Json type request and response .
public void callLogin(String sMethodToCall, String sUserId, String sPass) {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST, ConstantValues.ROOT_URL_LOCAL + sMethodToCall.toString().trim(), addJsonParams(sUserId, sPass),
// JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, object,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("onResponse", response.toString());
Toast.makeText(VolleyMethods.this, response.toString(), Toast.LENGTH_LONG).show(); // Test
parseResponse(response);
// msgResponse.setText(response.toString());
// hideProgressDialog();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("onErrorResponse", "Error: " + error.getMessage());
Toast.makeText(VolleyMethods.this, error.toString(), Toast.LENGTH_LONG).show();
// hideProgressDialog();
}
}) {
/**
* Passing some request headers
*/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
requestQueue.add(jsonObjectRequest);
}
public JSONObject addJsonParams(String sUserId, String sPass) {
JSONObject jsonobject = new JSONObject();
try {
// {"id":,"login":"secretary","password":"password"}
///***//
Log.d("addJsonParams", "addJsonParams");
// JSONObject jsonobject = new JSONObject();
// JSONObject jsonobject_one = new JSONObject();
//
// jsonobject_one.put("type", "event_and_offer");
// jsonobject_one.put("devicetype", "I");
//
// JSONObject jsonobject_TWO = new JSONObject();
// jsonobject_TWO.put("value", "event");
// JSONObject jsonobject = new JSONObject();
//
// jsonobject.put("requestinfo", jsonobject_TWO);
// jsonobject.put("request", jsonobject_one);
jsonobject.put("id", "");
jsonobject.put("login", sUserId); // sUserId
jsonobject.put("password", sPass); // sPass
// js.put("data", jsonobject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonobject;
}
public void parseResponse(JSONObject response) {
Boolean bIsSuccess = false; // Write according to your logic this is demo.
try {
JSONObject jObject = new JSONObject(String.valueOf(response));
bIsSuccess = jObject.getBoolean("success");
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(VolleyMethods.this, "" + e.toString(), Toast.LENGTH_LONG).show(); // Test
}
}
Hope am not too late to the party:
The issue is from the server side. If you are using PHP add the following lines at the top of your php api file (after includes)
$inputJSON = file_get_contents('php://input');
if(get_magic_quotes_gpc())
{
$param = stripslashes($inputJSON);
}
else
{
$param = $inputJSON;
}
$input = json_decode($param, TRUE);
Then to retrieve your values
$tag= $input['tag'];
Use GET in place of POST for using JsonObjectRequest
VolleySingleton.getInstance()
.add(new StringRequest(Request.Method.POST, urlToTest, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// do stuff...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// exception
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() {
return ServerApi.getRequiredParamsRequest(context);
}
}
);
...Initially, it was working for me
....Then all of a sudden it stopped working and I haven't made any changes to
the code
if you haven't made any changes to a previously working code then I suggest checking other parameters such as URL , as the IP address may change if you are using your own Computer as a server!

Categories

Resources