PUT Request for Json with Json array inside - android

I'm trying to update a PUT request which has a JSONArray inside it and I'm constantly getting a 500 error response. Here how the api structure is:
{
"imei": 514515854152463,
"franquia": "SAO",
"sistema": "PEGASUS",
"lista": 2055313,
"entregas":[
{
"codHawb": "02305767706",
"dataHoraBaixa": "2020-12-03T15:26:22",
"foraAlvo": 1000,
"latitude": 44.4545,
"longitude": 45.545,
"nivelBateria": 98,
"tipoBaixa": "ENTREGA"
}
]
}
I've tried the api in Postman to see if its working and it is. But when I'm trying it in the program using Volley I'm getting that error. I've tried volley and here is the code:
private void PutJsonRequest() {
try {
Map<String, String> postParam = new HashMap<String, String>();
postParam.put("imei", "514515854152463");
postParam.put("franquia", preferences.getFranchise());
postParam.put("sistema", preferences.getSystem());
postParam.put("lista", preferences.getListID());
postParam.put("dataHoraBaixa", "2020-12-03T15:26:22");
postParam.put("foraAlvo", "100");
postParam.put("latitude", "45.545");
postParam.put("longitude", " 45.554");
postParam.put("nivelBateria", "98");
postParam.put("tipoBaixa", "ENTREGA");
JsonObjectRequest request = new JsonObjectRequest(Request.Method.PUT, ApiUtils.GET_LIST + preferences.getListID(), new JSONObject(postParam), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "PUTonResponse: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "PUTonResponseError: " + error);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
String auth1 = "Basic "
+ Base64.encodeToString((preferences.getUserName() + ":" + preferences.getPass()).getBytes(),
Base64.NO_WRAP);
params.put("Authorization", auth1);
params.put("x-ver", "3.0");
params.put("x-ras", "rick");
params.put("Content-Type", "application/json");
return params;
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
queue.add(request);
} catch (Exception e) {
e.printStackTrace();
}
}
Here is the result in postman:1
Here is the result in postman:2
The problem is there is an array in the api, I've tried the above in the way if there are only JSON object but it is not working, please help me know if anything can be updated or done in different way for sending arrays either in volley or retrofit. Thanks.
//Edit:
I tried sending the params in another way and this was also giving the same 500 error:
JSONArray jsonArray=new JSONArray();
JSONObject jsonObj=new JSONObject();
try {
jsonObj.put("codHawb", "02305767706");
jsonObj.put("dataHoraBaixa", "2020-12-03T15:26:22");
jsonObj.put("foraAlvo", "100");
jsonObj.put("latitude", "-46.86617505263801");
jsonObj.put("longitude", " -23.214458905023452");
jsonObj.put("nivelBateria", "98");
jsonObj.put("tipoBaixa", "ENTREGA");
jsonArray.put(jsonObj);
Map<String, String> postParam = new HashMap<String, String>();
postParam.put("imei", "514515854152463");
postParam.put("franquia", preferences.getFranchise());
postParam.put("sistema", preferences.getSystem());
postParam.put("lista", preferences.getListID());
postParam.put("entregas",jsonArray.toString());

Finally figured it out, sending the PUT request in the form of api. FYI: If you have multiple json objects inside the array, just use a for loop, here is the working answer:
private void PutJsonRequest() {
JSONArray jsonArray=new JSONArray();
JSONObject jsonObj=new JSONObject();
JSONObject jsonObj1=new JSONObject();
try {
jsonObj.put("codHawb", "02305767706");
jsonObj.put("dataHoraBaixa", "2020-12-03T15:26:22");
jsonObj.put("foraAlvo", "100");
jsonObj.put("latitude", "45.222");
jsonObj.put("longitude", " 23.23452");
jsonObj.put("nivelBateria", "98");
jsonObj.put("tipoBaixa", "ENTREGA");
jsonArray.put(jsonObj);
jsonObj1.put("imei", preferences.getIMEI());
jsonObj1.put("franquia", preferences.getFranchise());
jsonObj1.put("sistema", preferences.getSystem());
jsonObj1.put("lista", preferences.getListID());
jsonObj1.put("entregas", jsonArray);
Log.e(TAG, "PutJsonRequest: "+jsonObj1 );
JsonObjectRequest request = new JsonObjectRequest(Request.Method.PUT, ApiUtils.GET_LIST + preferences.getListID(),jsonObj1, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "PUTonResponse: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "PUTonResponseError: " + error);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
String auth1 = "Basic "
+ Base64.encodeToString((preferences.getUserName() + ":" + preferences.getPaso()).getBytes(),
Base64.NO_WRAP);
params.put("Authorization", auth1);
params.put("x-versao-rt", "3.8.10");
params.put("x-rastreador", "ricardo");
// params.put("Content-Type", "application/json");
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
request.setTag(TAG);
queue.add(request);
} catch (Exception e) {
e.printStackTrace();
}
}
Comment if anyone has a doubt.

Related

How to set object to VolleyRequest(POST Request) in this type of API?

I have an API link to send post request for creating the order,
I tried to set Request in this way.
I want to send POST request same as request to send in my image (Postman).
I want to create order from cart using cartID and index of the cart, how to send please help me out from this.
Thank You :
public void postCreateOrderByCustomer(ArrayList<CartItem> cartItems) {
String token = sharedPreferences.getString(Constant.token, null);
String endPoint = "https://prettyyou.in/cake/pos/api/customers/create-order?token=" + token;
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
Map<String, String> payloadParams = new HashMap<String, String>();
for (int i = 0; i < cartItems.size(); i++) {
payloadParams.put("cart[" + i
+ "][id]", cartItems.get(i).getId());
}
Log.d(TAG, "postCreateOrderByCustomer: " + jsonObject);
System.out.println("endPointCartGet" + " " + endPoint.toString());
jsonObject = new JSONObject(payloadParams);
Log.d(TAG, "postCreateOrderByCustomer: " + jsonObject);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, endPoint, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d(TAG, "onResponseCustomer: " + response);
if (response.getBoolean("status")) {
Constant.orderId = response.getString("order_id");
Intent intent = new Intent(DeliveryDetailsActivity.this, PaymentDetailsActivity.class);
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse: " + error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return payloadParams;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return super.getHeaders();
}
};
RequestQueue queue = Volley.newRequestQueue(DeliveryDetailsActivity.this);
queue.add(jsonObjectRequest);
}
You can also use Stringrequest and object request or Jsonobject requst

how to parse JSON using Volley

i am using volley library for post data over api...in here the Content-Type is "application/json" ....
how can i implement this type of json data :
URL: Base_URL + dorequisition
{
"submitted_by_employee_id": 1,
"name": "Technolive SF for TC",
"bags_thana_wise": [
{
"tiger": "10000",
"extreme": "5000",
"opc": "3000",
"three_rings": "4000",
"buffalo_head": "2000",
},
],
"free_bag": "500",
"landing_price": "450",
"transport_cost_ex_factory_rate": "450",
"amount_taka": "four hundred fifty",
"bank_name": "IFIC Bank Limited",
"delivery_point": "Banani",
"upto_today": "450",
"bag_type": "swing",
"remark": "Good Cement",
"token": "2cbf1cefb6fe93673565ed2a0b2fd1a1"
}
api implementation sample :
public void APIRetailVisitInfo() {
for (int i = 0; i < retailVisitInfoList.size(); i++) {
System.out.println("token id:::" + token + " :::"+employee_id);
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("submitted_by_employee_id", employee_id);
jsonParams.put("retailer_name", retailVisitInfoList.get(i).getRetails_name());
jsonParams.put("retailer_phone", retailVisitInfoList.get(i).getRetailer_contact_no());
jsonParams.put("retailer_address", retailVisitInfoList.get(i).getRetails_address());
jsonParams.put("remarks", retailVisitInfoList.get(i).getRemarks());
jsonParams.put("token", token);
JsonObjectRequest myRequest = new JsonObjectRequest(
Request.Method.POST,
"http://technolive.co/retailvisitinfo",
new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
code = response.getString("code");
//token = response.getString("token");
} catch (JSONException e) {
e.printStackTrace();
}
if (code.equals("200")) {
System.out.println("APICompetetorBasedOnMArketPrice:::" + code + " :::");
}
// System.out.println("token:::" + token+" :::");*/
// verificationSuccess(response);
System.out.println("APICompetetorBasedOnMArketPrice:::" + response + " :::");
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// verificationFailed(error);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
String auth = token;
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("User-agent", "My useragent");
// headers.put("Authorization", auth);
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(RetailVisitInfoActivity.this);
requestQueue.add(myRequest);
// MyApplication.getInstance().addToRequestQueue(myRequest, "tag");
}
}
can anyone help me please........
It is rather simple. First let's start with bags_thana_wise. bags_thana_wise is a JSONArray. It contains one object. So lets create the object.
JSONObject json1 = new JSONObject();
json1.put("tiger","10000";
json1.put("extreme","5000";
and so on..Now put this json object into an array
JSONArray jsonArray = new JSONArray();
jsonArray.put(json1);
Now just add this array and other values to another json object
JSONObject finalObject = new JSONObject();
finalObject.put("submitted_by_employee_id","1");
finalObject.put("name","Technolive SF for TC");
//put the jsonArray
finalObject.put("bags_thana_wise",jsonArray);
finalObject.put("free_bag","500");
.
.
.
finalObject.put("token","2cbf1cefb6fe93673565ed2a0b2fd1a1");
Now make the following volley request
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.POST,
myURL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Handle response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PopupActivity.this,"Can not reach server",Toast.LENGTH_LONG).show();
}
}){
#Override
public String getBodyContentType(){
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() {
try {
return finalObject == null ? null: finalObject.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
};
RequestQueue requestQueue = Volley.newRequestQueue(RetailVisitInfoActivity.this);
requestQueue.add(jsonRequest);

Volley return 403 error

From two days i am trying to solve this issue but still i have no any result,why each and every time volley returning me 403 error. where i m wrong? i am using postman to check same webservice, it returns success result. But same thing when i am using in Android via volley or httpurlconnection getting 403 error.kindly help me to find my error.
This is my code which i have tried:
StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST, Constant.posturl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String result=response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse response = error.networkResponse;
int status = response.statusCode;
}
}) {
#Override
public Map<String, String> getHeaders() {
try {
headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
String credentials = Constant.USERNAME + ":" + Constant.PASSWORD;
String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT);
headers.put("Authorization", auth);
return headers;
} catch (Exception e) {
e.printStackTrace();
return headers;
}
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("title", heading_edit_text.getText().toString());
params.put("content", body_edit_text.getText().toString());
params.put("Slug", heading_edit_text.getText().toString());
params.put("date", currentDate);
return params;
}
};
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(50000, 3, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
Volley does provide a proper request for this which is called JsonObjectRequest.
String webAddress = "url here";
RequestQueue queue = Volley.newRequestQueue(this); // singletone here
JSONObject object = new JSONObject();
try {
object.put("title", heading_edit_text.getText().toString());
object.put("content", body_edit_text.getText().toString());
object.put("Slug", heading_edit_text.getText().toString());
object.put("date", currentDate);
} catch (JSONException e) {
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, webAddress,object, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject object) {
Log.d("RESPONSE", object.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d("RESPONSE", "That didn't work!");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> header = new HashMap<>();
// content type is not needed here
header.put("Authorization", "value here");
return header;
}
};
queue.add(request);
Change the "Content-Type" of your headers to "application/form-data"
ie,
headers.put("Content-Type", "application/form-data");
I was also face this issue in news api. But when I use Retrfit its work like a charm.

Android Volley JsonObjectRequest not send params

I'm trying to send a JsonObjectRequest to my server with some params, but seems like params doesn't arrive at the server. Before to post on SO I try all kind of suggestion found in google but no one works fine..
This is the code of my JsonObjectRequest:
RequestQueue queue = MySingleVolley.getInstance(ctx).
getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest(method,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("REQUEST_JSON_TO_SERVER", "Success: " + response.toString());
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("REQUEST_JSON_TO_SERVER", "Error: " + error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
#Override
protected Map<String, String> getParams() {
return params;
}
};
MySingleVolley.getInstance(ctx).addToRequestQueue(jsObjRequest);
And these are my param and others:
String url = "url";
//create the hashMap of parameters
database_zappapp db = new database_zappapp(getApplicationContext());
db.open();
HashMap<String, String> params = new HashMap<>();
params.put("action","myAction");
params.put("nomeutente", db.getUsernameLogged());
params.put("token", token);
db.close();
//Send the request to the server
Global.RequestJsonToServer(getApplicationContext(), url, Request.Method.POST, params);
Thanks in advance for the help!
Edit 2
I've changed my params in this creating a string jsonBody:
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("action","gcmUserRegister");
jsonObject.put("nomeutente",db.getUsernameLogged());
jsonObject.put("token",token);
}catch(JSONException e){
e.printStackTrace();
}
String requestBody = jsonObject.toString();
db.close();
and my request like this with getBody():
JsonObjectRequest jsObjRequest = new JsonObjectRequest(method,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("REQUEST_JSON_TO_SERVER", "Success: " + response.toString());
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("REQUEST_JSON_TO_SERVER", "Error: " + error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
return headers;
}
#Override
public byte[] getBody() {
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;
}
}
};
But already didn't work! =(
Postman screen:
No user found means that it enter in the if statement and so it works.. with android i receive "result": "null"
The postman screen with app/json:
I've found the solution!
The problem was in the server not in the client, I was getting the data using POST but from the client I was sending a json object so my new php is:
$data = json_decode(file_get_contents('php://input'), true);
//echo "Action: ".$action;
//Registrazione del token
if($data['action'] == "gcmUserRegister"){
......
Thanks al lot to BKS!!!
Change this part of your code:
`JsonObjectRequest jsObjRequest = new JsonObjectRequest(method,url,null ...`
To this:
`JsonObjectRequest jsObjRequest = new JsonObjectRequest(method,url,yourparams..`
Reason: if you are using the default Volley constructors thats the way to send params to Server.

Volley Post method for json object

data={
"request": {
"type": "event_and_offer",
"devicetype": "A"
},
"requestinfo": {
"value": "offer"
}
}
how to post this request from volley plz help
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST,url, null ,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
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/x-www-form-urlencoded");
return headers;
}
js is reffer to my jsson object ...... i make my jsson like this.....
JSONObject jsonobject_one = new JSONObject();
try {
jsonobject_one.put("type", "event_and_offer");
jsonobject_one.put("devicetype", "I");
JSONObject jsonobject_TWO = new JSONObject();
jsonobject_TWO.put("value", "event");
jsonobject = new JSONObject();
jsonobject.put("requestinfo", jsonobject_TWO);
jsonobject.put("request", jsonobject_one);
js = new JSONObject();
js.put("data", jsonobject.toString());
Log.e("created jsson", "" + js);
But it Not response the value what to do plzz help
first your json data:
JSONObject js = new JSONObject();
try {
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);
js.put("data", jsonobject.toString());
}catch (JSONException e) {
e.printStackTrace();
}
then your json request:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST,url, js,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
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;
}
Notice the header
and if you want to test in localhost use below code and set your url to connect your localhost server and ip address:
below code put all of your request in a text file, i tried it and it works
<?php
file_put_contents('test.txt', file_get_contents('php://input'));
?>

Categories

Resources