Code for Volley JsonObjectRequest
RequestQueue queue = Volley.newRequestQueue(context);
String url = "https://fcm.googleapis.com/fcm/send";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
Log.d("ERROR-->", response.toString());
}
},
new ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.d("ERROR-->","error => "+error.toString());
}
}
) {
Overriding header to provide authentication key
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "key=AIzaSyB_xxxxx_xxxxxxxxxxxxxxxx");
params.put("Content-Type", "application/json");
String mapAsJson = null;
try {
mapAsJson = new ObjectMapper().writeValueAsString(params);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
//Log.d("ERROR",""+mapAsJson);
Log.d("ERROR","-header-->"+params);
return params;
}
#Override
protected Map<String,String> getParams() throws AuthFailureError{
Map<String,String> params = new HashMap<String, String>();
Map<String,String> parent = new HashMap<String, String>();
Map<String,String> child = new HashMap<String, String>();
/* {
"notification":{
"title":"Mandeep ",
"text": "hello"
},
"to": "/topics/mandeep"
}*/
parent.put("title","Mandeep");
parent.put("text","Push Notification");
params.put("notification", String.valueOf(parent));
//params.put("", String.valueOf(child));
params.put("to","/topics/mandeep");
JSONObject obj=new JSONObject(params);
JSONArray array = null;
try {
array=new JSONArray(obj.toString());
} catch (JSONException e) {
e.printStackTrace();
}
//child.put("", String.valueOf(params));
Log.d("ERROR","-msg-->"+params);
return params;
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
queue.add(jsonObjReq);
Error => com.android.volley.ServerError
I tried to make successful requests using POSTMAN and I need help to change the code so that I can make the same request using volley.
Related
I am adding contacts to active campaign api but the request is not sending the post parameters.The parameters are being sent from postman but with volley its not working. I have tried sending params from the constructor also but no progress. Here is the code.
Map<String, String> params = new HashMap();
params.put("email", "wff#dd.com");
params.put("p[1]", "1");
//JSONObject parameters = new JSONObject(params);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
url="https://brumano.api-us1.com/admin/api.php?api_key=key&api_action=contact_add&api_output=json";
Log.d("url",url);
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,url,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("url",response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.d("url",error.toString());
error.printStackTrace();
}
}){
#Override
public byte[] getBody() {
HashMap<String, String> params2 = new HashMap<String, String>();
params2.put("email", "w#sss.com");
params2.put("p[1]", "1");
return new JSONObject(params2).toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded;";
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params2 = new HashMap<String, String>();
params2.put("email", "w#sss.com");
params2.put("p[1]", "1");
return params2;
}
}
};
queue.add(jsObjRequest);
Try this using StringRequest
StringRequest jsonObjRequest = new StringRequest(Request.Method.POST,
"https://brumano.api-us1.com/admin/api.php?api_key=key&api_action=contact_add&api_output=json",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("url",response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("volley", "Error: " + error.getMessage());
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("email", "w#sss.com");
params.put("p[1]", "1");
return params;
}
};
queue.add(jsonObjRequest);
check this, with stringRequest like this
//Tested on PostMan
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("userName", "cyborg91mv#gmail.com");
params.put("password", "qwerty");
System.out.println(params);
return params;
}
Now if your server expects json, then make jsonRequest
JSONObject jsonObjectBody = new JSONObject();
jsonObjectBody.put("userName", "cyborg91mv#gmail.com");
jsonObjectBody.put("password", "qwerty");
This is JsonObjectRequest and I am getting the error. Help me out......
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("email",email.getText().toString());
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.POST, json_url, new JSONObject(jsonParams), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d("Response", response.toString());
name.setText(response.getString("Name"));
mobile.setText(response.getString("Mobile"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#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;
}
};
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
Try using volley StringRequest, it seems, server is sending you Strings instead of JsonOBJECTS. If JsonObject is what you need, you must do some changes on the server side. If not try this:
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest request = new StringRequest(Request.Method.POST,
Addresses.LOGIN_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
Log.d("Response", jsonObject .toString());
name.setText(jsonObject .getString("Name"));
mobile.setText(jsonObject .getString("Mobile"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#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;
}
};
queue.add(request);
This might be your solution if your server receives values in json form.
JSONObject jsonobject= new JSONObject();
jsonobject.put("email",email.getText().toString());
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.POST, json_url, jsonobject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d("Response", response.toString());
name.setText(response.getString("Name"));
mobile.setText(response.getString("Mobile"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#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;
}
};
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
I am trying hit an api(written in PHP) and posting params with it.
Here is my code:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, null,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("prerna succes volley "+response.toString());
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("prerna fail volley "+error.toString());
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> pars = new HashMap<String, String>();
pars.put("Content-Type", "application/x-www-form-urlencoded");
return pars;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "login");
params.put("username", "abc#xyz.com");
params.put("pass", "a");
return params;
}
};
I always get invalid username/password which has been handled in api in case there is invalid username and password.In this case api is not receiving the params.
I tried to do it with retrofit and its working fine with it that means there is no problem at API coding. What am I missing here in case of volley?
Thanks for the support. I am able to solve the problem by changing JsonObjectRequest to StringRequest. i found Volley JsonObjectRequest Post parameters no longer work where I got to know that JsonObjectRequest creates some unexpected problems.
There is my code:
StringRequest jsonObjReq = new StringRequest(Request.Method.POST,
url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response.toString());
String no = jsonObject.getString("$PhoneNo");
} catch (JSONException e) {
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("prerna fail volley " + error.toString());
}
})
{
#Override
public String getBodyContentType() {
Map<String, String> pars = new HashMap<String, String>();
pars.put("Content-Type", "application/x-www-form-urlencoded");
//return pars;
return "application/x-www-form-urlencoded";
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "login");
params.put("username", "abc#xyz.com");
params.put("pass", "a");
return params;
}
};
However I am still trying to figure out why JsonobjectRequest did not work.
As far as I can tell by looking at JsonObjectRequest your 3rd parameter is null, and it indicates the JsonObject request - by the documentation "jsonRequest - A JSONObject to post with the request. Null is allowed and indicates no parameters will be posted along with request."
And after searching again, I saw this thread.
if you are sending your data in raw format you need to try this,first of all make json of your data to be post.
final JSONObject jsonBody = new JSONObject();
jsonBody.put("mobile", phoneNumber);
jsonBody.put("otp", otp.trim());
and you have to override these methods
#Override
public byte[] getBody() throws AuthFailureError {
return jsonBody.toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
if you also have header in your post request you also send that with by following type
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
String auth_token = "bearer" + prefs.getPreferencesString(context, "AuthToken").toString();
params.put("Authorization", auth_token);
return params;
}
Here is the whole code.
final JSONObject jsonBody = new JSONObject();
jsonBody.put("mobile", phoneNumber);
jsonBody.put("otp", otp.trim());
StringRequest sr = new StringRequest(Request.Method.POST, Constraints.Base_URL + "/api/v1/verifyotp", new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
progressDialog.dismiss();
JSONObject jsonObject = new JSONObject(response);
int status = jsonObject.getInt("status");
String token = jsonObject.getString("token");
prefs.setPreferencesString(OtpActivity.this, "AuthToken", token);
if (status == 1) {
startActivity(new Intent(getApplicationContext(), WelcomeScreenActivity.class));
overridePendingTransition(R.anim.right_in, R.anim.left_out);
} else if (status == 0) {
Toast.makeText(OtpActivity.this, "Please Enter Otp!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(OtpActivity.this, "Invalid otp please try again!!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
return jsonBody.toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
MyApplication.getInstance().addToReqQueue(sr, "jreq");
}
} catch (Exception e) {
}
Try migrating to getHeaders and remove getParams
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "login");
params.put("username", "abc#xyz.com");
params.put("pass", "a");
return pars;
}
Or - Reuse the getParams method
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = getParams();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
If it is a body request all you need to do is add the extra parameter.
JSONObject body = new JSONObject();
body.put("action", "login");
body.put("username", "abc#xyz.com");
body.put("pass", "a");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, body,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("prerna succes volley "+response.toString());
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("prerna fail volley "+error.toString());
}
});
the JSONObject is this:
{"tag":"login","success":1,"error":0,"name":"pb","dir":"DH","br":"LL","gr":"IW","email":"empty"}
logcat says:
Value Access of type java.lang.String cannot be converted to JSONObject
the running an AsyncTask beside, and it works. why the volley-code says its a string? The answer from the server is a JSONObject for sure.... Why it says its a String?
private void makeJsonObjectRequest() {
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
String dir = response.getString("dir");
Log.d("dir", dir);
} catch (JSONException e) {
e.printStackTrace();
Log.d("JSONException", e.getMessage().toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("onErrorResponse", error.getMessage().toString());
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("name", name);
params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
I don't know why it's append but I got the same issue with volley with the same type of request (HTTP POST + HEADER + PARAMS)
I fix it using StringRequest and parsing it manually. Try in this way
StringRequest postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
Log.d(TAG, "Success "+ s.toString());
try {
JSONObject data = new JSONObject(s);
String dir = data.getString("dir");
Log.d("dir", dir);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error response " + error.getMessage());
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("name", name);
params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
While the workaround with the StringRequest works fine, I found the "real" problem which is a very unintuitive default implementation in Volley which causes the POST request to turn into a GET. Check out my answer here
for a solution.
I am using Volley for a login function but I get unexpected response code 400 for https.
It works on WiFi but does not work on a cellular network and the problem only happens on selected phone models. Below is my code.
public void LoginRequest(final String username,final String password,final ActionResponse success,final Action err ){
RequestQueue queue = MVolleyRequests.getInstance(mContext).getRequestQueue();
StringRequest sr = new StringRequest(com.android.volley.Request.Method.POST,LOGIN_URL,
new Listener<String>() {
#Override
public void onResponse(String response) {
success.action(MError.getError(Integer.parseInt(response)));
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
err.action();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("id", username);
params.put("pwd", password);
params.put("version", "2.5" );
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
return params;
}
};
sr.setRetryPolicy(new DefaultRetryPolicy(
60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MVolleyRequests.getInstance(mContext).addToRequestQueue(sr);
}
Try this out:
JSONObject params = new JSONObject();
try {
params.put("id", username);
params.put("pwd", password);
params.put("version", "2.5" );
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
url, params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject 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
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.setRetryPolicy(new DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
getRequestQueue(jsonObjReq);