How to create a post request in volley android with parameters - android

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);

Related

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);

how to post parameters as a json in android while calling any api

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": []
}
]
}

Android Volley POST Parameters

I need to call an api that expects a string array as a POST parameter. So for an example of an API definition:
POST api/names
POST parameter expected is an array of names and some other attributes like below:
{ names: [ "John", "Bill" ], department: "Engineering" }
I am currently using a custom Volley framework as described in the Android documentation but it seems like the parameters from Volley can only be passed as a Map of (String, String as key and value). I already have the array from my Android app, ready to be passed as a post parameter but this Volley expects a String.
I tried to convert my array using Arrays.toString(myStringArray) and passed it like below but it does not work.
String[] namesArray = new String[1];
namesArray[0] = "Bill";
Map<String, String> mapParams = new HashMap<String, String>();
mapParams.put("department", "Computer Science");
mapParams.put("names", Arrays.toString(namesArray));
// Then call the Volley here passing the mapParams.
How can I call the api that expects a String of array when I can only use a String from Volley?
I will give you full code to post JsonObject on volley, through POST method.
JSONObject js = new JSONObject();
try {
js.put("genderType", "MALE");
}
} catch (JSONException e) {
e.printStackTrace();
}
String url = "LINK TO POST/";
// Make request for JSONObject
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST, url, js,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Response_Code from Volley" + "\n" + response.toString() + " i am king");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e(TAG, "Error: " + error.getMessage());
NetworkResponse response = error.networkResponse;
if (error instanceof ServerError && response != null) {
try {
String res = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
// Now you can use any deserializer to make sense of data
Log.e(TAG, "onErrorResponse: of uploadUser" + res);
// JSONObject obj = new JSONObject(res);
} catch (UnsupportedEncodingException e1) {
// Couldn't properly decode data to string
e1.printStackTrace();
}
}
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
Log.e(TAG, "uploadUser: near volley new request ");
// Adding request to request queue
Volley.newRequestQueue(this).add(jsonObjReq);
}
Put anything you need in the js object with key and its values
Use JsonObjectRequest and simply pass a JSONObject. There's a full example here
public void makePostRequest(final Map<String,String> myMap,String MEDIA_URL,final VolleyResponse callback)
{
VolleySingleton VS;
Log.e("URL",MEDIA_URL);
VS=VS.getInstance();
RequestQueue rq=VS.getRequestQueue();
StringRequest stringRequest = new StringRequest(Request.Method.POST,MEDIA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
callback.onSuccess(s);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
callback.onError();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new Hashtable<String, String>();
Iterator<Map.Entry<String, String>> iterator = myMap.entrySet().iterator();
while(iterator.hasNext()) {
Map.Entry<String,String> pairs = (Map.Entry<String,String>)iterator.next();
String value = pairs.getValue();
String key = pairs.getKey();
params.put(key,value);
Log.e("Key","Value"+value);
}
return params;
}
};
//Creating a Request Queue
// RequestQueue requestQueue = Volley.newRequestQueue(this);
DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(0, -1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(retryPolicy);
//Adding request to the queue
rq.add(stringRequest);
}
Where the VolleyResponse is a simple custom interface like this
public interface VolleyResponse {
void onSuccess(String resp);
void onError();
}

Hi, I have issue in my Volley post method

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();
}

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