Hi, I have issue in my Volley post method - android

I want to post the data as json formatted,but i dont know how to do that please help me to solve this issue.Normally i use the Volley post method as below (Its not any formatted type),its perfectly working for me,but now my backend developer ask me to post details as json format.
String url=" http://10.10.4.27/teacherapp_dxb/index.php/teacher_app_cn/login?user_id=EMP263&password=thanzeel";
StringRequest strReq = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
}
else {
// order error
String responseMsg = jObj.getString("response");
Toast.makeText(Viewactivity.this,
"ooola kirane"+ responseMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Viewactivity.this,
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Post product to orderplacing url
Map<String, String> params = new HashMap<String, String>();
params.put("user_id,"EMP263")
params.put("password","thanzeel");
return params;
}
};
// Adding request to queue
AppController.getInstance().addToRequestQueue(strReq);
}
In the above code i send the data wit out any format,but the backend developer need get the data as json format.So please help me to solve this issue.

You can do it like below in your getParams()
Map<String, String> params = new HashMap<String, String>();
params.put("user_id","EMP263");
params.put("password","thanzeel");
JSONObject jsonObjectParam = new JSONObject(params);
Map<String,String > postParams = new HashMap<>();
postParams.put("key",""+jsonObjectParam);
you can ask for this "key" to your backend team.
Hope it helps!

If you want to send data in JSONArray from android app try this way :
public String makeJSON(String s1,String s2,String s3){
JSONArray jsonArray = new JSONArray();
JSONObject data = new JSONObject();
try {
data.put("dataparam1",s1);
data.put("dataparam2", s2);
data.put("dataparam3", s3);
} catch (JSONException e) {
e.printStackTrace();
}
jsonArray.put(data);
JSONObject jsonData = new JSONObject();
try {
jsonData.put("dataArray", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
String jsonStr = jsonData.toString();
System.out.println("jsonString: "+jsonStr);
return jsonStr;
}
And if you just want to send data in JSONObject try this :
public String createjson(String s1,String s2,String s3)
{
JSONObject jsonObj = new JSONObject();
JSONArray jsonArr = new JSONArray();
JSONObject jsonObject = new JSONObject();
try {
jsonObj.put("dataparam1",s1);
jsonObj.put("dataparam2",s2);
jsonObj.put("dataparam3",s3);
jsonArr.put(jsonObj);
jsonObject.put("cartItems", jsonArr);
} catch (JSONException e) {}
return jsonObject.toString();
}

Related

How to create a post request in volley android with parameters

I am building an android application that should communicates with the server using volley, it sends the server a request with data in it that should be processed on server and results, sent back.
I am always getting an error from the server, and It's most probably because I couldn't build the request right.
This is the format of the request :
POST API/{RESOURCE}
Content-type: application/json
{
"documents" :
[
{ "image" : "<base64-encoded image>", "type": "id_front or id_back" },
{ "image" : "<base64-encoded image>", "type": "id_front or id_back" }
…
],
"token" : "<access_token_string>"
}
This is how i tried to achieve it, is it right ? I am not sure if the problem is with this code but it's most probable that it's in it.
JSONObject parameters = new JSONObject();
JSONObject[] jsonObjects;
jsonObjects = new JSONObject[1];
try {
Map<String , String> im = new HashMap<>();
im.put("image",imageStringBase64);
im.put("type","id_front");
jsonObjects[0] = new JSONObject(im);
parameters = parameters.put("token", "****");
parameters= parameters.put("documents", jsonObjects);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, API_URL, parameters, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
StringBuilder formattedResult = new StringBuilder();
formattedResult.append(response);
Log.d(TAG, "jsonObjectResponse : " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "ErrorResponse called " + "error code: " + error.networkResponse.statusCode);
}
})
{
/** Passing some request headers* */
#Override
public Map getHeaders() throws AuthFailureError {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
return headers;
}
};
mQueue.add(jsonObjectRequest);
Try building your request like below:
JSONObject requestObj;
try {
requestObj = new JSONObject();
JSONArray arr = new JSONArray();
JSONObject obj1 = new JSONObject();
obj1.put("image", imageStringBase64);
obj1.put("type","id_front");
JSONObject obj2 = new JSONObject();
obj2.put("image", imageStringBase64);
obj2.put("type","id_back");
arr.put(obj1);
arr.put(obj2);
requestObj.put("documents", arr);
requestObj.put("token", "****");
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, requestObj,
listener, errorListener);

How to parse JSON using Volley?

i have some json output like this
{
"message": "success",
"battery": "AHAJAJ1DH13T0021",
"data": {
"id": 6,
"userId": 3,
"shopId": 1,
"transactionStatus": "PENDING",
"expiredAt": "2019-01-04T03:01:18.878Z",
"updatedAt": "2019-01-04T02:01:18.916Z",
"createdAt": "2019-01-04T02:01:18.916Z",
"paymentId": null,
"batteryNo": null
},
"shopData": {
"id": 1,
"name": "test1",
"tel": "555",
"address": "cikarang",
"description": "showroom",
"latitude": "-6.307923199999999",
"longitude": "107.17208499999992",
"open_time": "10.00",
"battery_available": 16,
"battery_booked": 1,
"status": 1,
"createdAt": "2018-12-28T03:59:55.156Z",
"updatedAt": "2019-01-04T02:01:18.940Z"
}
}
and i implement using volley like this
StringRequest request = new StringRequest(Request.Method.POST, ApiService.ORDER_BATTERY, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
BookBattery bookBattery = new BookBattery();
JSONObject jsonObject = new JSONObject(response);
if (!jsonObject.has("success")) {
JSONObject object = jsonObject.getJSONObject("battery");
String data = object.getString("");
JSONArray jsonArray = jsonObject.getJSONArray("data");
} else {
Log.e("Your Array Response", "Data Null");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error is ", "" + error);
}
}) {
//This is for Headers If You Needed
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json; charset=UTF-8");
params.put("token", TokenUser);
return params;
}
//Pass Your Parameters here
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("shopId", String.valueOf(shopId));
//params.put("Pass", PassWord);
return params;
}
};
AppController.getInstance().addToRequestQueue(request, tag_json_obj);
but not working, please help thanks a lot
Use http://jsonviewer.stack.hu/ [To see json data structure]
braces {} its an JSONObject
brackets [] its an JSONArray
public void parseJson() {
try {
JSONObject jsonObject = new JSONObject(jsonParsing);
boolean isSuccess = jsonObject.getString("message").contains("success");
if (isSuccess) {
JSONObject jsonObjectData = jsonObject.getJSONObject("data");
String userId = jsonObject.getString("userId");
JSONObject jsonObjectShopData = jsonObject.getJSONObject("shopData");
String name = jsonObject.getString("tel");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
You are not getting JSONArray anywhere, your response object has multiple JSONObject
JSONObject jsonObject = new JSONObject(response);
if (!jsonObject.has("success")) {
JSONObject object = jsonObject.getJSONObject("battery");
JSONOnject jsonObject2= jsonObject .getJSONObject("data");// here you need to change.
String batteryNo=jsonObject2.getJSONObject("batteryNo");
JSONOnject jsonObject3= jsonObject1.getJSONObject("shopData");
String address=jsonObject2.getJSONObject("address");
} else {
Log.e("Your Array Response", "Data Null");
}
You can use some lib for Volley (e.g. VolleyEx), together with Gson, to parse the JSON Object to a Map in Java.
i.e. using GsonObjectRequest instead of StringRequest
developer.android.com has the code, but there are also libs doing that for you.
example HERE
Try this
StringRequest request = new StringRequest(Request.Method.POST, ApiService.ORDER_BATTERY, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
BookBattery bookBattery = new BookBattery();
JSONObject jsonObject = new JSONObject(response);
String message = jsonObject.getString("message");
if (message.equalsIgnoreCase("success")) {
String battery = jsonObject.getString("battery");
JSONObject dataObject = jsonObject.getJSONObject("data");
JSONObject shopDataObject = jsonObject.getJSONObject("shopData");
int dataId = dataObject.getInt("id");
int dataUserId = dataObject.getInt("userId");
int dataShopId = dataObject.getInt("shopId");
} else {
Log.e("Your Array Response", "Data Null");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error is ", "" + error);
}
}) {
//This is for Headers If You Needed
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json; charset=UTF-8");
params.put("token", TokenUser);
return params;
}
//Pass Your Parameters here
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("shopId", String.valueOf(shopId));
//params.put("Pass", PassWord);
return params;
}
};
AppController.getInstance().addToRequestQueue(request, tag_json_obj);
here i only parse "id", "userId" & "shopId" from dataObject. Rest can be parse in similar way.
Before do it I will suggest you please read about the json Array and Json Object.
Here the solution.
HashMap<String, String> params = new HashMap<String, String>();
params.put("your json parameter name", json parameter value);
// params.put("device_id", deviceID);
Log.d("response11", String.valueOf(params));
String Url ="your server url";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Url,
new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG + "JO", String.valueOf(response));
try {
String msgObject = response.getString("message");
Log.d("response","msgObject");
}catch (JSONException e){
String jsonExp = e.getMessage();
Log.d(TAG + "JE", jsonExp);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String volleyErr = error.getMessage();
Log.d(TAG + "VE", volleyErr);
}
});
requestQueue.add(jsonObjectRequest);
this sufficient for print you server response. check response in logcat.

failed jsonArrayRequest

MY function content to make jsonArrayRequest is:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST,
FilesUsed.url_display_thought, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONObject jsonObject1 = response.getJSONObject(0);
JSONObject jsonObject2 = response.getJSONObject(1);
if (jsonObject1.getBoolean("error")) {
ArrayList<String> list = new ArrayList<>();
list.add(jsonObject2.getString("message"));
displayThought(list);
} else {
int count = 0;
ArrayList<String> list = new ArrayList<>();
while (count < response.length()) {
try {
JSONObject jsonObject = response.getJSONObject(count);
String thought = jsonObject.getString("post");
list.add(thought);
count++;
} catch (JSONException e) {
e.printStackTrace();
}
}
displayThought(list);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", "sainiakshay04");
return params;
}
};
RequestHandler.getInstance(this).addToRequestQueue(jsonArrayRequest);
The content of the php it is using is:
require_once '../app/display_personal_account.php';
$response=array();
if(isset($_POST['email'])){
$db = new display_personal_account($_POST['email']);
$res=$db->get_info_added("shared_content");
if($res==1){
$response=$db->display_shared_content();}
else{
$response[]['error']=true;
$response[]['message']="No Content To Display ";}
}
else{
$response[]['error']=true;
$response[]['message']="ERROR: INVALID REQUEST";
}
echo json_encode($response);
?>
but the output it is displaying is ERROR:INVALID REQUEST, although I'm binding email using getParams, isset of php is not working and going to else part.
HELP!
You're checking isset($_POST['email']) but you send null parameter in the JsonArrayRequest.
For now, JsonArrayRequest only supports the JsonArray parameter.
There are two things that you need to do :
Send the email in the JsonArray parameter
JSONObject request = new JSONObject();
request.put("email", userEmail);
JSONArray arrayParam = new JSONArray();
arrayParam.put(request);
....
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST,
FilesUsed.url_display_thought, arrayParam, ...
Get the email in the PHP
require_once '../app/display_personal_account.php';
$response=array();
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
if(isset($input[0]['email'])){
$db = new display_personal_account($input[0]['email']);
....
After that, you should just work fine :)

How to POST JSON Object In Android using Volly Library below type of Json?

Here is my code :
{
"VisitorDetails":[
{
"Name":"Ramesh",
"Gender":"Male",
"Age":24,
"MobileNo":9502230173,
"LandLine":"040140088",
"EmailId":"rameshkandula24#gmail.com",
"CreatedOn":"08-25-2016",
"Address":"Hyderabad",
"Profession":"Software",
"FamilyMembers":5,
"HomeTown":"Gannavaram",
"MedicalHealing":"Noooooo",
"Isinterestedwithcompanies":1,
"IsBetterlivingStandards":1,
"IsInterestedinConference":1,
"VisitorExcites":[1,2,3]
"jsonkey" : "rUinterested"
}
]
}
try {
JSONArray arry = new JSONArray();
JSONObject iner = new JSONObject();
iner.put("Name", "nmae");
//all detail to iner
arry.put(iner);
JSONObject outer = new JSONObject();
outer.put("VisitorDetails", arry);
}
catch (Exception e){
}
final JSONObject jsonObject=new JSONObject();
try {
JSONArray jsonArray=new JSONArray();
JSONObject innerobject=new JSONObject();
innerobject.put("Name",Name);
innerobject.put("Address",Country);
jsonArray.put(innerobject);
jsonObject.put("VisitorDetails",jsonArray);
}catch (Exception e){
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL,jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// do something...
Toast.makeText(MainActivity.this, "your data successfully register", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
Toast.makeText(MainActivity.this, "your data not register", Toast.LENGTH_SHORT).show();
}
}) {
/**
* Passing some request headers
*/
#Override
protected Map<String, String> getParams() {
Map<String, String> param = new HashMap<String, String>();
param.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
return param;
}
};
Update : add this in your gradle(app level)
compile 'com.android.volley:volley:1.0.0'
developing from Bansal ans .
your json data
JSONArray arry = new JSONArray();
try {
JSONObject jsonobject_one = new JSONObject();
jsonobject_one.put("Name", "Name");
// add all details like this
arry.put(jsonobject_one);
JSONObject jsonobject_TWO = new JSONObject();
jsonobject_TWO.put("VisitorDetails", arry);
}catch (JSONException e) {
e.printStackTrace();
}
Then Your jsonRequest
JsonArrayRequest jsonArryReq = new JsonArrayRequest(
Request.Method.POST,url, arry,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray 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
protected Map<String, String> getParams()
{
Map<String, String> param = new HashMap<String, String>();
if (!GetMethod) {
param.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
return param;
}
return param;
}

Adding POST parameters to Android Volley JsonObjectRequest

Good afternoon everyone
I did a volley connection to my localserver. It turns out, the connection works fine but my parameters are not getting accepted in my MysqlPHP script.
I believe the parameters are not getting sent correctly.
Here is the code
try {
RequestQueue jr = Volley.newRequestQueue(this);
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
Log.d("The paramet ready", "Ready to go");
JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("The response", response.toString());
progressDial.hide();
JSONArray json = null;
try {
json = response.getJSONArray("result");
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (json.getString(0).equalsIgnoreCase("0")) {
Log.d("JsonString: -> ", json.toString());
progressDial.hide();
toast();
} else {
startagain();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
progressDial.hide();
}
}
);
jr.add(jsonObject);
I encountered a similar issue. I had a server API which returned a JSON Object response, so JsonObjectRequest was the go-to request type, but the server didn't like that my body was in JSON format, so I had to make a few changes to my request.
Here's what I did (adapted to your code):
JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.POST, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("The response", response.toString());
progressDial.hide();
JSONArray json = null;
try {
json = response.getJSONArray("result");
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (json.getString(0).equalsIgnoreCase("0")) {
Log.d("JsonString: -> ", json.toString());
progressDial.hide();
toast();
} else {
startagain();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
progressDial.hide();
}
}
)
{
#Override
public byte[] getBody()
{
try
{
final String body = "&username=" + username + // assumes username is final and is url encoded.
"&password=" + password // assumes password is final and is url encoded.
return body.getBytes("utf-8");
}
catch (Exception ex) { }
return null;
}
#Override
public String getBodyContentType()
{
return "application/x-www-form-urlencoded";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError
{
Map<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
return headers;
}
};
Here, I'm not sending any JSON Object as the post body, but instead, I'm creating the post body on my own, form url encoded.
I'm overriding the following methods:
getBody - I'm creating the body of the post exactly the way the server wanted it - form url encoded.
getBodyContentType - I'm telling the server what the content type of my body is
getHeaders - I'm telling the server to return the result in JSON format. This might not be necessary for you.
If your API return a JSON array, then you should use a JsonArrayRequest, not a JsonRequest.

Categories

Resources