Volley Request Body not being execulted - android

I have the following method in Volley.When i call the method only one Log info gets printed in log.
private void loadFromCloudAPI() {
Log.i("apiresponse","inside api call");
queue = VolleySingleton.getInstance().getQueue();
CacheRequest attendanceDetailsCache = new CacheRequest(Request.Method.POST, URL, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
final String jsonString;
Log.i("apiresponse","inside api call");
try {
jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
Log.i("apiresponse",jsonString);
JSONArray jsonArray= new JSONArray(jsonString);
renderDataInTheAttendanceDetailsLayout(jsonArray);
} catch (UnsupportedEncodingException|JSONException e) {
Log.i("apiresponse",e+"");
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String ,String > data = new HashMap<>();
data.put("authenticate","false");
data.put("class_id","1");
data.put("section_id","4");
data.put("student_id","1");
return super.getParams();
}
};
attendanceDetailsCache.setTag(this);
queue.add(attendanceDetailsCache);
}
Output::
apiresponse: inside api call
Only one info Log ? How ? I cannot log the response nor the error , when i try the same thing using ARC in browser i get the response. What might be the issue ?

Related

Trying to send POST from android to node server using volly but the json body is empty on the server

private void postRequest() {
// Request a string response from the provided URL.
// Instantiate the RequestQueue.
String url = "http://10.0.0.9:3000/hello";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
Log.i("*********", "******");
response.put("Hello", "World");
}catch(JSONException e){
Log.i("JSONERROR", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
Log.i("*********", error.toString());
}
});
jsonObjectRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 1000;
}
#Override
public int getCurrentRetryCount() {
return 1000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});
This is the Android code
app.post('/hello', function(req,res){
console.log(JSON.stringify(req.body))
})
This is the node js code
So the problem im having is that im printing the body to the console but it keeps showing up empty. As you can see in the postRequest method ive put 'hello as key' and 'world as value' in the jsonobject. So it is calling the correct post request, the body is just empty and cant figure out why that is.
Edit-----
Ive checked the content with wireshark and content length is 0 so im not sending anything it seems. if im understanding this correctly
You are not sending anything inside of your POST body request, that's why you are getting an empty response at your server-side.
For sending POST parameters, you will need to override getParams() method:
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
map.put("param1", "hello");
map.put("param2", "This is a post request");
return map;
}
Here is the complete example:
private void postRequest() {
// Request a string response from the provided URL.
// Instantiate the RequestQueue.
String url = "http://10.0.0.9:3000/hello";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
Log.i("*********", "******");
response.put("Hello", "World");
}catch(JSONException e){
Log.i("JSONERROR", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
Log.i("*********", error.toString());
}
}) { // HERE TO ADD POST PARAMETERS
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
map.put("param1", "hello");
map.put("param2", "This is a post request");
return map;
}
};
jsonObjectRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 1000;
}
#Override
public int getCurrentRetryCount() {
return 1000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});

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

Volley onResponse method not working

I'm using Volley to send Post request.I'm trying to send jsonObject to server.This is my source
public void sendDicieIDToServer(JSONObject jsonObject)
{
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.e("response is", "Response " + jsonObject.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
NetworkResponse errorRes = volleyError.networkResponse;
String stringData = "";
if(errorRes != null && errorRes.data != null){
try {
stringData = new String(errorRes.data,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
Log.e("Error",stringData);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Authorization",uhfScannerModel.getToken());
params.put("Content-Type", "application/json");
return params;
}
};
HandsetApplication.getInstance().addToRequestQueue(jsonObjectRequest);
}
I successfully created JsonObject and when I run my app and try to debug it, onErrorResponse method has called and stringData String contains real json result. I don't know what is a wrong and why onErrorResponse method calling.
User this link for Volley
Here i made volley reusability where you can apiCall easy way..
https://github.com/sikander-kh/Volley-Reusability

Android Volley POST JsonObject and get JsonArray or JsonObject or Other response

in volley we have some ability to retrieve data from server such as jsonObject,jsonArray and String. in this below sample we can get simply jsonObject or jsonArray response from server,
public static void POST(HashMap<String, String> params, final Listeners.ServerResponseListener listener) {
JsonObjectRequest req1 = new JsonObjectRequest(ApplicationController.URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("Response:", response.toString());
if (listener != null)
listener.onResultJsonObject(response);
else
Log.e(TAG,"Error: SetServerResponse interface not set");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error: ", error.getMessage());
}
});
ApplicationController.getInstance().addToRequestQueue(req1);
}
my problem is i want to send jsonObject from this method and get jsonArray or jsonObject from server, and i can not get simply array from server with this method. for example i must be filter server response with this jsonObject:
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");
params.put("search_count", "10");
params.put("order_by", "id");
server return jsonArray and i can not get that with Volley response
Looking at the source code of JsonArrayRequest. There is a constructor which takes in a JSONObject. You should check it out
public class RetreiveData {
public static final String TAG = RetreiveData.class.getSimpleName();
public static void POST(String localhost, final HashMap<String, String> params, final Listeners.ServerResponseListener listener) {
StringRequest post = new StringRequest(Request.Method.POST, localhost, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
if (listener != null)
listener.onResponse(response.toString());
else
Log.e(TAG, "Error: SetServerResponse interface not set");
} catch (Exception e) {
e.printStackTrace();
Log.d("Error: ", e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error: ", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = params;
return map;
}
#Override
public RetryPolicy getRetryPolicy() {
setRetryPolicy(new DefaultRetryPolicy(
5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
return super.getRetryPolicy();
}
};
ApplicationController.getInstance().addToRequestQueue(post);
}
}

How I send a JsonObject and recive a JsonArray

While I was testing the "volley" library, a doubt arose me regarding the method "post".
The thing is that I have been working with JsonObject until now, for that I used the following code and it works. In this method I send and JsonObject and receive another JsonObjet, I had no problem with it.
Now my doubt is, How can I do to send a JsonObject and receive an ArrayObject?
I am really lost with this, I will really appreciate your help, thanks in advance
public void testPost(String url, final String tag, JSONObject obj) {
//final ProgressDialog pDialog = new ProgressDialog(context);
//pDialog.setMessage("Loading...");
//pDialog.show();
JsonObjectRequest jsonObjReqpost = new JsonObjectRequest(Request.Method.POST,
url, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//test
Log.d("SendRequestJsonPost", response.toString());
//pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error.networkResponse != null && error.networkResponse.data != null) {
error = new VolleyError(new String(error.networkResponse.data));
}
String fail = handlingErrors.resolverErrors(error.toString());
//Log.d("SendRequestJsonPost", fail);
//pDialog.hide();
}
}) {
//header
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("charset", "utf-8");
return headers;
}
};
jsonObjReqpost.setTag(tag);
Singleton.getInstance(context).addToRequestQueue(jsonObjReqpost);
}
You can use the following method to get JsonArray as response.
public JsonArrayRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener)
{
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(),
listener, errorListener);
}
Please refer this answer for more details.
public class nameOfClass extends AsyncTask {
String response;
//This process is work in Background
#Override
protected String doInBackground(String... params) {
SocketConnection connection = new SocketConnection();
String token;
//Tocken name that is send to server
token = "TockenName|" + "|";
try {
response = connection.EstablishConnection(token);
String message = "Sorry Fail to connect";
if (response.equals(message)) {
onPostExecute(message);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return response;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// In this method you can open loading msg
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
//Json object
JSONArray array = new JSONArray(result);
for (int i = 0; i < array.length(); i++) {
//Hear traverse the loop and get the data
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Categories

Resources