Android Json Arraylist to Server with Restful Web service - android

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 ...

Related

How to fix JSONException Error in Volley library?

I am trying to send a JSON object request with two parameters and in response trying to get an array from the api call. However, I am getting exception parse error in Error listener. A post request is sent when the button is clicked. The func takes two parameters but fails to get response, the function directly goes to on response error listener
private void validate_log(String num) {
/*buttonNumCheck.setVisibility(View.INVISIBLE);
final ProgressBar pBar=(ProgressBar)findViewById(R.id.progressBarLogin);
pBar.setVisibility(View.VISIBLE);*/
buttonNumCheck.setInProgress(true);
buttonNumCheck.setEnabled(false);
final String Org_id="81";
final String url="http://xya/api";
RequestQueue rq=Volley.newRequestQueue(this);
JSONObject js=new JSONObject();
try {
js.put("parm1", num);
js.put("parm2", Org_id);
final String requestBody=js.toString();
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjReq=new JsonObjectRequest(
Request.Method.POST, url, js,
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
buttonNumCheck.setEnabled(true);
buttonNumCheck.setInProgress(false);
String stresponse=response.toString();
Toast.makeText(getApplicationContext(),"REPOSE="+response,Toast.LENGTH_SHORT).show();
System.out.println("RESPONSE= "+response);
try {
JSONArray heroArray = response.getJSONArray("");
// Toast.makeText(DeviceCheck_Activity.this, "Welcome Back"+ [1], Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
Log.e("Error", "Response Error", e);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DeviceCheck_Activity.this, "Response error= " + error, Toast.LENGTH_LONG).show();
/*mdToast=MDToast.makeText(getApplicationContext(), "Oops something went wrong!!",
Toast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();*/
buttonNumCheck.setInProgress(false);
buttonNumCheck.setEnabled(true);
Log.e("Error", "Response Error", error);
}
}) {
#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.setShouldCache(false);
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.add(jsonObjReq);
}
The error response I am getting is
com.android.volley.ParseError: org.json.JSONException: Value [{"store_id":11,"store_name":"Gomati District Main Store"},{"store_id":13,"store_name":"Main Seed Store"}] of type org.json.JSONArray cannot be converted to JSONObject
Your Problem can be solved in 2 ways :
First:)
Using JSONArrayRequest instead of JSONbjectRequest.
Your JSONObjectRequest returns an JSONObject response while your response is an JSONArray therefore java can not convert it and your application crashes.
Change you request as below:
JSONArrayRequest jsonArrReq=new JSONArrayRequest(//changed
Request.Method.POST, url, js,
new Response.Listener<JSONArray>() {
public void onResponse(JSONArray response) {
JSONArray heroArray = response;//changeed
/* rest of your code */
} catch (JSONException e) {
e.printStackTrace();
Log.e("Error", "Response Error", e);
}
}
},
jsonArrReq.setShouldCache(false);
jsonArrReq.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.add(jsonArrReq);
Second :)
Using StringRequest instead of JSONObjectRequest. String request returns an String response which lets you do what ever you want with your response.
Change you request as below :
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray heroArray = new JSONArray(response);
/* rest of your code */
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", "Response Error", error);
/*rest of your code */
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : js.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", js, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
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));
}
};
}
stringRequest.setShouldCache(false);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.add(stringRequest);
Use the JsonArrayRequest like thisas your response is JsonArray .
JsonArrayRequest jsonObjReq = new JsonArrayRequest(Request.Method.POST, url, js,
new Response.Listener<JSONArray>() {
public void onResponse(JSONArray response) {
buttonNumCheck.setEnabled(true);
buttonNumCheck.setInProgress(false);
String stresponse = response.toString();
try {
for (int i = 0; i < response.length(); i++) {
JSONObject object = response.getJSONObject(i);
String id = object.getString("store_id");
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("Error", "Response Error", e);
}
}
}
Tried all the solutions didn't worked but thank you guys for your help. I actually found the solution from another question posted in stack overflow page. Here is the solution:
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//JSONArray jsonArray_1=new JSONArray(response);
System.out.println("RESPONSE= " + response);
JSONArray jsonArray=new JSONArray(response);
json_stringarr=new String[jsonArray.length()];
if(jsonArray.length()>0) {
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
//String web_page=jsonObject1.getString("awb_no");
String store_id=jsonObject1.getString("store_id");
String store_name=jsonObject1.getString("store_name");
json_stringarr[i]=store_id+" - "+store_name;
Toast.makeText(getApplicationContext(), "RESPOBBSE= " + json_stringarr[i], Toast.LENGTH_SHORT).show();
System.out.println("JSON ARRAY=" + json_stringarr[i]);
System.out.println("JSON Object=" + jsonObject1);
}
}
else{
Toast.makeText(getApplicationContext(),"Login ceredentils are incorrect",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
MDToast mdToast=MDToast.makeText(getApplicationContext(), "Something went wrong!!", Toast.LENGTH_SHORT, MDToast.TYPE_WARNING);
mdToast.show();
error.printStackTrace();
}
}) {
#Override
public byte[] getBody() {
// String body="{\"param1\":"+num+",\"param2\":\"81"\"}";
String body="{\"parm1\":"+num+",\"parm2\":\"81\"}";
return body.getBytes();
}
/*#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("param1", num);
params.put("param2", Org_id);
return params;
}*/
#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;
}
};
I did it by sending a String request and then overriding the getBody() method and then it worked like a charm. Thanks again for all your help.

How to send {data:[{id:"11:}]} request to server in using volley and pass ObjectRequest in body

I want to pass {"data:"[{"id":"12"}]} in volley request body.
private void reqrej(final String currentLat) {
String insertData = "http://www.xxxxxxxx.com/makeinforequest.php";
final StringRequest stringRequest = new StringRequest(Request.Method.POST, insertData, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("json", response.toString());
tv.setText(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
// String mylong = String.valueOf(mCurrentLocation.getLongitude()).toString();
Map<String, String> params = new HashMap<String, String>();
params.put("data", "");
//where I can type request code?
return checkParams(params);
}
private Map<String, String> checkParams(Map<String, String> map) {
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next();
if (pairs.getValue() == null) {
map.put(pairs.getKey(), "");
}
}
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
please guide me how to pass this things in android with volley , i try so many times but not success.
Try This
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
try {
JSONObject jsonObject=new JSONObject();
JSONArray jsonArray=new JSONArray();
JSONObject idJson=new JSONObject();
idJson.put("id","12");
jsonArray.put(jsonObject);
jsonObject.put("data",jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
final String mRequestBody = jsonObject.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("LOG_RESPONSE", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_RESPONSE", 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;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
Try this
try
{
JSONObject obj = new JSONObject();
JSONArray jsonArray = new JSONArray();
obj.put("id", "12");
jsonArray.put(obj);
JSONObject jsonObjectdata = new JSONObject();
jsonObjectdata.put("data", jsonArray);
Log.i("Json Response",""+ jsonObjectdata.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can use JsonObjectRequest
Here is the example you can try https://stackoverflow.com/a/28344904/6676466
in this example there is pass your jsonString inside new JSONObject(postParam).

Nodejs req.body shows empty from Android Volley

Android Code:
private void registerUser(){
final String username = "subrata";
final String password = "banerjee";
final String email = "test_email";
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_USERNAME,username);
params.put(KEY_PASSWORD,password);
params.put(KEY_EMAIL, email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
I'm trying to send http request using Android Volley to my node.js server (expressjs). Its hitting the server and getting the response but when I'm printing the req.body in node.js its shows {} (empty). I'm new to Android and unable to figure out the reason. Please someone guide me.
Call this method in OnResponse GetResponse(response);
And the method will be
private void GetResponse(String res){
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(res);
JSONArray result = jsonObject.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject jo = result.getJSONObject(i);
String temp = jo.getString("what_ever");
String temp1 = jo.getString("what_ever_1");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
This will get you the response in String format fetched from json.
private void registerUser(){
JSONObject jsonBodyObj = new JSONObject();
try{
jsonBodyObj.put("mAtt", "+1");
jsonBodyObj.put("mDatum","+2");
jsonBodyObj.put("mRID","+3");
jsonBodyObj.put("mVon","+4");
}catch (JSONException e){
e.printStackTrace();
}
final String requestBody = jsonBodyObj.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#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");
headers.put("User-agent", "My useragent");
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;
}
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

Android Send POST of JSON raw body with volley

I have to send a post with voley but when i try to send raw body as requested, instead of a response a get this error
******com.android.volley.ServerError******: {"message":"No user account data for registration received."}
i tried the same in postman and it works perfect, how can i fix it in my code?
raw body that works in postman ->
{
"camp1": {
"value": "value"
},
"camp2": {
"value": "value2"
}
}
this is what it is in my code ->
public void requestRegistrationInfo(#NonNull final String camp1, #NonNull final String camp2,final Listener listener) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(new JsonObjectRequest(
Request.Method.POST, URL,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.v("IT WORK");
listener.onSuccess();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("******" + error.toString() + "******", getErrorMessage(error));
listener.onFailure();
}
})
{
#Override
protected Map<String,String> getParams() {
Map<String, String> map = new HashMap<>();
map.put("{camp1", "value");
map.put("camp2", "value");
return map;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("header1", "header1");
map.put("header2", "header2");
return map;
}
});
}
what can i do to send raw json correctly and don't show the error?
In normal case JSONObject request didn't hit the getParams() method , this method only for String request and passing key value pair data payload. If you want to pass a raw body with JSON data , first you have to format your data as server accepted.
In your case this is your data
{
"camp1":{
"value":"value1"
},
"camp2":{
"value2":"value2"
}
}
You have to convert your data to Server accepted JSON format like this
JSONObject jsonObject = new JSONObject();
jsonObject.put("value", "value1");
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("value2", "value2");
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("camp1", jsonObject);
jsonObject2.put("camp2",jsonObject1);
//jsonObject2 is the payload to server here you can use JsonObjectRequest
String url="your custom url";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST,url, jsonObject2, new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
//TODO: Handle your response here
}
catch (Exception e){
e.printStackTrace();
}
System.out.print(response);
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
error.printStackTrace();
}
});
JsonObjectRequest will accept the payload as json in its constructor after the url parameter we will pass the data
This is tested Code try this:
private void multipartRequestWithVolly() {
String urll = "your_url";
progressDialog.show();
StringRequest request = new StringRequest(Request.Method.POST, urll, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
if (!TextUtils.isEmpty(response)) {
Log.e(TAG, "onResponse: " + response);
textView.setText(response);
} else {
Log.e(TAG, "Response is null");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Log.e(TAG, "onErrorResponse: " + error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
hashMap = new HashMap<>();
hashMap.put("OPERATIONNAME", "bplan");
hashMap.put("mcode", "298225816992");
hashMap.put("deviceid", "dfb462ac78317846");
hashMap.put("loginip", "192.168.1.101");
hashMap.put("operatorid", "AT");
hashMap.put("circleid", "19");
return hashMap;
}
};
AppController.getInstance().addToRequestQueue(request);
}
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
JSONObject jsonBody = new JSONObject();
jsonBody.put("Title", "Android Volley Demo");
jsonBody.put("Author", "BNK");
final String requestBody = jsonBody.toString();
StringRequest stringRequest = 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 requestBody == null ? null : encodeParameters(requestBody , getParamsEncoding());
} 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) {
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);
} catch (JSONException e) {
e.printStackTrace();
}
Please check with the edited getBody()
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : encodeParameters(requestBody , getParamsEncoding());
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
If you calling any REST-API then note that that's payload always be in JSON format. therefor you can use an object body for payload like this way.
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", input_loginId.getText().toString());
params.put("password", input_password.getText().toString());
and you can pass this on method like this way
JsonObjectRequest logInAPIRequest = new JsonObjectRequest(Request.Method.POST, YOUR-URL,
new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
input_errorText.setText(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
input_errorText.setText("Error: " + error.getMessage());
}
});

How to send a POST request with JSON body using Volley?

How to pass these parameter into POST method using Volley library.
API link: http://api.wego.com/flights/api/k/2/searches?api_key=12345&ts_code=123
Screenshot of JSON structure
I tried this but again facing error.
StringEntity params= new StringEntity ("{\"trip\":\"[\"{\"departure_code\":\","
+departure,"arrival_code\":\"+"+arrival+","+"outbound_date\":\","
+outbound,"inbound_date\":\","+inbound+"}\"]\"}");
request.addHeader("content-type", "application/json");
request.addHeader("Accept","application/json");
Please visit here for the details of API.
Usual way is to use a HashMap with Key-value pair as request parameters with Volley
Similar to the below example, you need to customize for your specific requirement.
Option 1:
final String URL = "URL";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "token_value");
params.put("login_id", "login_id_value");
params.put("UN", "username");
params.put("PW", "password");
JsonObjectRequest request_json = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
//Process os success response
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(request_json);
NOTE: A HashMap can have custom objects as value
Option 2:
Directly using JSON in request body
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
JSONObject jsonBody = new JSONObject();
jsonBody.put("firstkey", "firstvalue");
jsonBody.put("secondkey", "secondobject");
final String mRequestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("LOG_VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_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;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
this is an example uses StringRequest
StringRequest stringRequest = new StringRequest(Method.POST, url, listener, errorListener) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put("api_key", "12345");
map.put("ts_code", "12345");
return map;
}
};
OkHttpClient okHttpClient = new OkHttpClient();
ContentValues values = new ContentValues();
values.put(parameter1Name, parameter1Value);
values.put(parameter2Name, parameter2Value);
RequestBody requestBody = null;
if (values != null && values.size() > 0) {
FormEncodingBuilder formEncoding = new FormEncodingBuilder();
Set<String> keySet = values.keySet();
for (String key : keySet) {
try {
values.getAsString(key);
formEncoding.add(key, values.getAsString(key));
} catch (Exception ex) {
Logger.log(Logger.LEVEL_ERROR, CLASS_NAME, "getRequestBodyFromParameters", "Error while adding Post parameter. Skipping this parameter." + ex.getLocalizedMessage());
}
}
requestBody = formEncoding.build();
}
String URL = "http://example.com";
Request.Builder builder = new Request.Builder();
builder.url(URL);
builder.post(requestBody);
Request request = builder.build();
Response response = okHttpClient.newCall(request).execute();

Categories

Resources