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'));
?>
Related
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.
I am trying to send data to my server. I create a JsonObject and I pass it as a parameter when creating the JsonObjectRequest. It doesn't give any error, but it is not returning anything. Tried with postman and it is working fine.
This is my code:
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("firstname", "asd");
jsonBody.put("lastname", "asd");
jsonBody.put("id", "1");
} catch (JSONException e) {
e.printStackTrace();
}
//creating a JsonObjectRequest
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, showPlayersUrl,
jsonBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray players;
try{
players = response.getJSONArray("Players");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
Ok, found the problem. Server side i wasn't accepting the data as json format. Just had to add this and it works:
$_POST = json_decode(file_get_contents('php://input'), true);
Try it:
RequestQueue queue = Volley.newRequestQueue(this);
private void makeJsonObjReq() {
showProgressDialog();
Map<String, String> postParam= new HashMap<String, String>();
postParam.put("un", "xyz#gmail.com");
postParam.put("p", "somepasswordhere");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Const.URL_LOGIN, new JSONObject(postParam),
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();
}
}) {
#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;
}
};
jsonObjReq.setTag(TAG);
queue.add(jsonObjReq);
}
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);
I am new to Android development, I need to post parameters as a JSON while calling any API method.
I am passing as a array list:
List<NameValuePair> params = new ArrayList<NameValuePair>();
Please give any suggestions.
Thank you
finally i found solution using volley library, it's working fine now
private void callApiWithJsonReqPost() {
boolean failure = false;
uAddress="133 Phùng Hưng, Cửa Đông, Hoàn Kiếm, Hà Nội, Vietnam";
addressTag="work address";
String callingURl="put your url here"
JSONObject jsonObject=null;
try {
jsonObject=new JSONObject();
jsonObject.put("address", uAddress);
jsonObject.put("type", "insert");
jsonObject.put("tag", addressTag);
} catch (Exception e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
callingURl, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("new_address" ,"sons=="+response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("error", "Error: " + error.getMessage());
}
}) {
/**
* 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;
}
};
// Adding request to request queue
Singleton_volley.getInstance().addToRequestQueue(jsonObjReq,"1");
}
params.add(new BasicNameValuePair("key",data));
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
I wrote a library for parsing and generating JSON in Android http://github.com/amirdew/JSON
for example:
JSON generatedJsonObject = JSON.create(
JSON.dic(
"someKey", "someValue",
"someArrayKey", JSON.array(
"first",
1,
2,
JSON.dic(
"emptyArrayKey", JSON.array()
)
)
)
);
String jsonString = generatedJsonObject.toString();
result:
{
"someKey": "someValue",
"someArrayKey": [
"first",
1,
2,
{
"emptyArrayKey": []
}
]
}
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;
}