I'm trying to send a post to my backend API through volley with params inside of it but I don't receive anything in the backend
Android Method:
private void sendPayments() {
RequestQueue requestQueue = Volley.newRequestQueue(PaymentActivity.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, clientCheckout, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "onResponse: "+response);
if(response.toString().contains("Successful")) {
Log.e(TAG, "onResponse: Successful");
} else {
Log.e(TAG, "onResponse: Failed");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: "+error);
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
if(paramHash == null)
return null;
Map<String, String> params = new HashMap<>();
for (String key: paramHash.keySet()) {
params.put(key, paramHash.get(key));
}
Log.e(TAG, "getParams: "+params);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
requestQueue.add(stringRequest);
}
and here is the backend code:
router.post('/checkout', (req, res, next) => {
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
const nonceFromTheClient = query.nonce;
console.log(req.params);
console.log(req.query);
console.log(query);
gateway.transaction.sale({
amount: "10.00",
paymentMethodNonce: nonceFromTheClient,
options: {
submitForSettlement: true
}
}, function (err, result) {
if(err) {
console.log(err);
} else {
console.log(result);
}
});
})
All logs in the backend return nothing! but the Log.e(TAG, "getParams: "+params); logs the data so the data exists but I don't know if its being sent and the backend can't read it or it's not sent from the beginning
Related
I am using post method in volley. I searched and found that getHeader() is used to send header in request.The solution was to use JSONObject request instead of string request(which i am using currently) but is there a way of sending header through this method? Because in that case I will have to modify a lot of code in many classes. Sorry for the English, I am not a native speaker.
The request parameter is a json object. I am sending the parameters using following code.
mRequestQueue = Volley.newRequestQueue(getContext());
mStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", "onResponse: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("This is the error", "Error :" + error.toString());
}
})
{
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() throws AuthFailureError {
HashMap<String, String> params2 = new HashMap<String, String>();
params2.put("AssigneeId",userid);
params2.put("IssueStatus", "5");
return new JSONObject(params2).toString().getBytes();
}
};
mRequestQueue.add(mStringRequest);
This request also has StringRequest. Please use the getHeaders() in this way:
public void requestWithSomeHttpHeaders() {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.somewebsite.com";
StringRequest getRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.d("ERROR","error => "+error.toString());
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("User-Agent", "Nintendo Gameboy");
params.put("Accept-Language", "fr");
return params;
}
};
queue.add(getRequest);
}
For JsonObjectRequest:
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,url,
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(tag, response.toString());
activity.hideDialog();
try {
activity.onRequestServed(response, code);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(tag, "Error: " + error.getMessage());
Log.e(tag, "Site Info Error: " + error.getMessage());
Toast.makeText(activity.getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
activity.hideDialog();
try {
activity.onRequestServed(null,code);
} catch (JSONException e) {
e.printStackTrace();
}
}
}) {
/**
* 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");
headers.put("key", "Value");
return headers;
}
};
I want to send some data to the server and the data has some parameters and it has a large body of JSON. I am trying to use aVolley to send this data.
The getParams() function is never called for some reason.
Here is my code:
final StringRequest stringReq = new StringRequest(Request.Method.POST, API_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (Util.IS_DEBUG_LOGGABLE) {
Log.d(TAG, "onResponse: Sent Data");
}
Toast.makeText(getContext(), R.string.config_changed, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (Util.IS_DEBUG_LOGGABLE) {
Log.d(TAG, "onErrorResponse: Data Not Sent Because server could not verify");
}
Toast.makeText(getContext(), getString(R.string.msg_data_not_sent, error), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> pars = new HashMap<>();
if (Util.IS_DEBUG_LOGGABLE) {
Log.d(TAG, "getParams: Called");
}
pars.put(PARAM1, "testf18");
pars.put(PARAM2, "Save");
return pars;
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
if (Util.IS_DEBUG_LOGGABLE) {
Log.d(TAG, "getBody: Called");
}
return response.toString().getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", response.toString(), "utf-8");
return null;
}
}
};
RequestHelperClass.addToRequestQueue(stringReq, getContext());
Please help.
I am looking to do as per the image says:
Following is the code I am trying to implement from that image:
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://api.kairos.com/enroll";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Log.i("Response is: " , response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// mTextView.setText("That didn't work!");
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("app_id", "4985f625");
params.put("app_key", "aa9e5d2ec3b00306b2d9588c3a25d68e");
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
Now I do not get how to add that JSONObject part into my POST Request, and also how to add the Content-Type Header.
I found a similar question here. See the code below. You have to override the getBodyContentType method.
public String getBodyContentType()
{
return "application/json";
}
for content type header you can do the following
StringRequest request = new StringRequest(Request.Method.PUT,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
listener.onResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(#NonNull VolleyError error) {
if (error.networkResponse != null) {
errorListener.onErrorResponse(error.networkResponse.statusCode, null);
} else {
Log.e(TAG, "An error occurred while trying to verify sms: ", error);
errorListener.onErrorResponse(500, null);
}
}
}) {
#NonNull
#Override
protected Map<String, String> getParams() {
return data;
}
#NonNull
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type",
"application/x-www-form-urlencoded");
return headers;
}
};
And for send Json object I suggest create Json object like this
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("11", 3);
jsonObject.put("12", 4);
jsonObject.put("13", 5);
} catch (JSONException e) {
e.printStackTrace();
}
Then you can pass this object as string by jsonObject.toString() and pass it in parameters like pass any string like the following
#NonNull
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("json", jsonObject.toString();
return params;
}
How to manage the case if I only want to send text, or only image not both like this code does. As in this code volley gives error when either message or imageBitmap is not provided.
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, CHAT,
new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
Toast.makeText(MyActivity.this, response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.toString());
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put(MESSAGE, message);
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
params.put(FILE, new DataPart("Image.jpg", imageBitmap));
return params;
}
};
VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
i'm trying to update some data with android volley but not working. and with postman it works.
my code:
private void aceptarAlerta()
{
mRequestQueue = VolleySingleton.getInstance().getmRequestQueue();
SharedPreferences preferencia = getSharedPreferences("ComuniUsuario", Context.MODE_PRIVATE);
token = preferencia.getString("ComuniToken", null);
StringRequest stringRequest = new StringRequest(Request.Method.PUT, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Respuesta: ", response);
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("estado", "true");
params.put("cuidador", Tmensaje[2]);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "Token " + token);
return headers;
}
#Override
public RetryPolicy getRetryPolicy() {
return new DefaultRetryPolicy(
15000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
}
};
mRequestQueue.add(stringRequest);
}
and if i delete params from code i dont get any error response from server.
i don't know what's the problem, i think have a logical error.