posting params as json in android volley - android

I am using volley library for making request. I need to post param as json array because I am receiving it on the other side as json array. How can I convert my params to Json array?
here is my code
public void SendData() {{
final StringRequest strReq = new StringRequest(Request.Method.POST, GET_STUDENTS_BY_ID, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.v("failedd",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", "Registration Error: " + error.getMessage());
}
})
{
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", user_id);
params.put("student_id", studId);
params.put("to", tomail);
params.put("subject", subjects);
params.put("description", descriptions);
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;
}
};
AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
}
please help..

public void SendData() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", user_id);
params.put("student_id", studId);
params.put("to", tomail);
params.put("subject", subjects);
params.put("description", descriptions);
JSONObject parameters = new JSONObject(params);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,GET_STUDENTS_BY_ID,parameters,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());
}
}) {
#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;
}
};
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}

Related

Url working in Retrofit but not working in Volley

I have Url for Login. Its working and give response in Postman and Retrofit but not working with volley.
In volley its give error: com.android.volley.RedirectError
Why i geeting RedirectError. url working and give response in retrofit as well in postman.
Here is my Code:
public void Login(){
final String REGISTER_URL = "Here_My_Url";
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("onResponse", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("eee123",error.toString());
Toast.makeText(getApplicationContext(), error.getMessage(),
Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("user_email", st_email);
params.put("password", st_pass);
Log.e("params", " " + params);
}
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
return headers;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(0, -1,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
stringRequest.setShouldCache(false);
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}

volley unable to send data to server

I am using this code
StringRequest stringRequest = new StringRequest(Request.Method.POST,
uploadUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("sfhyoutubeghhj",response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//loading.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> prams = new HashMap<>();
prams.put("aaaa", "1111");
prams.put("bbbb", "2222");
return prams;
}
#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;
}
};
RequestQueue requestQueuea = Volley.newRequestQueue(this);
requestQueuea.add(stringRequest);
Request is going to server and response is also coming but its not sending any variable from android either in GET or POST method
and i m just using
print_r($_REQUEST);
at PHP end
I think there was a problem with Request queue only
working fine with this code # Ali Azhar's Answer
StringRequest sr = new StringRequest(Request.Method.POST, url , new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Log.d(TAG, ""+error.getMessage()+","+error.toString());
}
}){
#Override
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put("id", "28");
params.put("value", "1");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String, String>();
headers.put("Content-Type","application/x-www-form-urlencoded");
headers.put("abc", "value");
return headers;
}
};
AppController.getInstance().addToRequestQueue(sr);

Sending post parameters with JsonObjectRequest volley to active campaign api

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

BasicNetwork.performRequest - Unexpected response code 400 (POST)

When I am trying to fetch data through rest api using Volley StringRequest or JsonObjectRequest. I always get 400 error. Its working fine with the postman. Http request method is POST, Content-Type is application/x-www-form-urlencoded. I have also checked my parameter spelling and it looks fine to me. I have tried with both StringRequest and JsonObjectRequest, result is E/Volley: [10283] BasicNetwork.performRequest: Unexpected response code 400. Below is my code. I have attached a screenshot.
Here is the new screenshot
StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
viewHelper.hideDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
viewHelper.hideDialog();
}
}){
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", email);
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;
}
#Override
public String getBodyContentType(){
return "application/x-www-form-urlencoded";
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(stringRequest, "Authenticating User");
I have alos tried with volley JSONObjectRequest
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", email);
params.put("password", password);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, AppConfig.URL_LOGIN, new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#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;
}
};
Can anyone please help me in fixing this issue.
Below is the working example of POST request using Volley library.
Add this to your build.gradle (Module:app) -
compile 'com.mcxiaoke.volley:library:1.0.19'
StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
progressDialog.dismiss();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
if(jsonObject.has("success")){
if(jsonObject.getBoolean("success") == true){
JSONObject userObject = new JSONObject(jsonObject.getString("user"));
Map<String, String> loginDetails = new HashMap<String, String>();
loginDetails.put(KEY_IS_LOGGED_IN, "true");
loginDetails.put(ACCESS_TOKEN, jsonObject.getString(ACCESS_TOKEN));
loginDetails.put(USERID, userObject.getString(USERID));
loginDetails.put(FIRSTNAME, userObject.getString(FIRSTNAME));
loginDetails.put(LASTNAME, userObject.getString(LASTNAME));
loginDetails.put(EMAIL, userObject.getString(EMAIL));
session = new SessionManager(_myActivity);
session.setLogin(loginDetails);
Intent intent = new Intent(LoginActivity.this, SearchActivity.class);
intent.putExtra("FROM_ACTIVITY", "LoginActivity");
startActivity(intent);
LoginActivity.this.finish();
}else{
btnLogin.setClickable(true);
btnLogin.setEnabled(true);
Toast.makeText(getApplicationContext(), "Username or Password does not matched!", Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
btnLogin.setClickable(true);
btnLogin.setEnabled(true);
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Something went wrong, Please try agian", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
progressDialog.dismiss();
btnLogin.setClickable(true);
btnLogin.setEnabled(true);
}
}){
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", email);
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;
}
#Override
public String getBodyContentType(){
return "application/x-www-form-urlencoded";
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
RequestQueue mRequestQueue = Volley.newRequestQueue(getApplicationContext());
mRequestQueue.add(stringRequest);
Please comment if anyone faced issue with above code.
Thanks to everyone who tried to help me.
A 400 means bad request the data sent by the you to the server didn't follow the rules.So check your parameter or spelling of these parameter which is required by server.
So check those try again hope it work for you :)
Unexpected response code 400 means Bad Reuest.
This Response is caused by sending wrong parameters with the URL.
To solve:
Check every parameter with spelling.
Make sure if response is obtained in string or in object. stringRequest or JSONObjectReuest
Also check Content-type
use this as Content-type
#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;
}
For JsonObjectReuest use:
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "BLah");
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d("Response:", response.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error: ", error.getMessage());
}
});

Volley-Lib -> String cannot be converted to JSONObject with a real JSONObject

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.

Categories

Resources