Volley Post JsonObjectRequest ignoring parameters while using getHeader and getParams - android

I am trying to connect API url="api adress" which accepts two header types application/json to reponce in json and application/xml to reponce in xml. I need to hit JSON with json parameters and responce will be in json format too. Using android volley Post request with JsonObjectRequest setting headers using getHeaders it connects to server but getParams to set parameters does not work.
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Constants.BASE_URL + Constants.LOGIN, null, response,
response_error) {
/**
* 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");
return headers;
}
#Override
protected Map<String, String> getPostParams()
throws AuthFailureError {
// TODO Auto-generated method stub
Map<String, String> params = new HashMap<String, String>();
params.put("key", "value");
return params;
}
};
// implementation of listeners
Response.Listener<JSONObject> response = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
Log.e("responce", response.toString());
// msgResponse.setText(response.toString());
hideProgressDialog();
}
};
Response.ErrorListener response_error = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error responce", error.getMessage());
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
};
//get params never get called
//i also tried alternative to send params but does not works.
Map<String, String> params = new HashMap<String, String>();
params.put("key", "value");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Constants.BASE_URL + Constants.LOGIN, new JSONObject(params), response,
response_error) {
/**
* 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");
return headers;
}
};
any type of help will be appretiated, Thanks in advance.

Volley will ignore your Content-Type setting, if you want to modify the content-type, you can override the getBodyContentType method :
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, url,
new JSONObject(params), response, response_error) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
}
for why volley ignore your parameters? take a look at my another answer.

Volley JsonObjectRequest Post request not working
Take the other answer from that post wich starts with: You can create a custom JSONObjectReuqest

Related

Sending form data in volley post request

The postman response is this image:
This is the code i am using to send the data in the post request. Although i am getting a 400 response code from this.
StringRequest stringRequest = new StringRequest(Request.Method.POST,
API.ADD_PAYMENT,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
onBackPressed();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(AddPaymentActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("amount", "123");
params.put("description", "Not Paid");
params.put("customer", "1");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json; charset=UTF-8");
headers.put("Authorization", "token 0ee1248c5a84e8b1e36a8a15da48c0bb7580926c");
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(AddPaymentActivity.this);
requestQueue.add(stringRequest);
First of all why don't you use JsonObjectRequest instead of StringRequest when you're using application/json as your talking language with server? Second have you tried passing your parameters to the other request constructor like below?
Map<String, Object> params = new HashMap<>();
params.put("amount", 123);
params.put("description", "Not Paid");
params.put("customer", 1);
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.POST, API.ADD_PAYMENT, new JSONObject(params), new Response.Listener<JSONObject>() {
...
Passing your headers are essential so the rest of you code remains as it is.

How to send POST request in JSON and response in JSON using volley (Android)

private void login(){
// Post params to be sent to the server
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", username);
params.put("password", password);
JsonObjectRequest req = new JsonObjectRequest(login_URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.v("Response:%n %s", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("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;
}
};
// add the request object to the queue to be executed
AppController.getInstance().addToRequestQueue(req);}
I got below error:
E/Volley: [1] 10.onErrorResponse: Error:
i dont know where the problem
json send as post:
{
"":"",
"":"",
"":"",
}
json response as:
{"":""}
You should add the Request.Method.POST as the first parameter of your new JsonObjectRequest method. Also scrap out the new 'JSONObject(params)'.
Now override the getParams() method just above your getParams override and add the content of your login method there. You should return params.
It should work. Let me know if you have any challenges. :).
A very good example would be here
Volley library can be integrated using grader and if you want to know about implementation of Requests in volley then following link can give you all types of requests you can make with volley and how to implement it .
Here you go
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

JsonObjectRequest returns 415

I have a server in tomcat and I am trying to make a request from my android device. All I get back is 415. I havent been able to replicate the error with fiddler by sending a defective Json. The server does not react to my request. I do have println() at every step just in case.
try {
params.put("userId", 2);
params.put("latitude", lon1);
params.put("longitude", lat1);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
errTextBox.setText(params.toString());
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, params.toString(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
msg.setText(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
msg.setText("not ok " + 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));
queue.add(jsonObjReq);
Not a dublicate because my request is done with a JsonObjectRequest. Also removing the charset did not help.
Well, I may have made a boo boo.
In my server software I was already parsing the recived string to Json.
So the is that I needed to send plain text...
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "text/plain; charset=utf8");
return headers;

Pass a JsonObject in Volley as POST parameter

I have an API endpoint which needs parameters to be sent as JsonObject in a POST request.
The response which I will get is not Json, but rather a small CSV string.
The Code is
stringRequest = new StringRequest(Request.Method.GET, "http://apitest.eezyrent.com/api/userauthentication/SignUp",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Toast.makeText(getApplication(), response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplication(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> jsonParams2 = new HashMap<String, String>();
jsonParams2.put("vcFName", firstname.getText().toString());
jsonParams2.put("vcLname", lastname.getText().toString());
jsonParams2.put("vcMobileNo", phone_no.getText().toString());
jsonParams2.put("vcGender", gender_short);
jsonParams2.put("vcEmailAddress", email.getText().toString());
jsonParams2.put("vcPassword", password.getText().toString());
jsonParams2.put("vcFBID", "");
jsonParams2.put("intLoginUserID", "");
jsonParams2.put("SignUpFrom", "Web");
jsonParams2.put("intloginid", "");
jsonParams2.put("AlreadyRegister", "");
return jsonParams2;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put( "charset", "utf-8");
return headers;
}
};
The above code is heavily inspired by using answers from this community, but this does not seem to solve the problem for me.
I get Volley Error 405.
E/Volley﹕ [112549] BasicNetwork.performRequest: Unexpected response code 405 for http://myurl
Infact If I used AsyncTask instead of Volley, With the same json as parameters and the same endpoint url. It works!! The AsyncTask code was found from this question. Java HttpClient changing content-type?
But I want to use Volley, What could be the solution to this?
Sample JSON Object
{"vcFName":"Ron","vcLname":"Weasley","vcMobileNo":"555888999","vcGender":"M","vcEmailAddress":"someone#somewhere.com","vcPassword":"123456","vcFBID":"","intLoginUserID":'',"SignUpFrom":"Web","intloginid":"","AlreadyRegister":""}
You need to use JsonObjectRequest class. Pass your params as json object in the 3rd parameter of the JsonObjectRequest class. Below is a small snippet:
Map<String, String> jsonParams2 = new HashMap<String, String>();
jsonParams2.put("vcFName", firstname.getText().toString());
jsonParams2.put("vcLname", lastname.getText().toString());
jsonParams2.put("vcMobileNo", phone_no.getText().toString());
jsonParams2.put("vcGender", gender_short);
jsonParams2.put("vcEmailAddress", email.getText().toString());
jsonParams2.put("vcPassword", password.getText().toString());
jsonParams2.put("vcFBID", "");
jsonParams2.put("intLoginUserID", "");
jsonParams2.put("SignUpFrom", "Web");
jsonParams2.put("intloginid", "");
jsonParams2.put("AlreadyRegister", "");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
YourUrl, new JsonObject(jsonParams2),
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/json");
headers.put( "charset", "utf-8");
return headers;
}
};
Step 1: Make model class parsable/Serializable.
Step 2: Override toString() in model class.
Step 3:
Map<String,JSONObject> params = new HashMap<>();
JSONObject object = null;
try{
object = new JSONObject(classObject.toString());
}catch (Exception e){
}
params.put("key", object);
JSONObject objectParams = new JSONObject(params);
Step 4: Send objectParams with volley JSONObject request.
Done!!!

Volley not calling getParams() for standard POST request

I am trying to post some parameters to my rails API using Volley in Android. This is the code:
I tried with two log statements, one in getParams() and another in getHeaders(). The one in getHeaders() is logged while the other one is not. Why is volley ignoring getParams()?
{
//full_name,email,password are private variables defined for this class
String url = "http://10.0.2.2:3000/users/sign_up.json" ;
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
}) {
#Override
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
//This does not appear in the log
Log.d(TAG,"Does it assign params?") ;
params.put("name", full_name.getText().toString());
params.put("email",email.getText().toString());
params.put("password", password.getText().toString());
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
//This appears in the log
Log.d(TAG,"Does it assign headers?") ;
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
// Adding request to request queue
VHelper.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
Using StringRequest in place of JsonObjectRequest
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);
The third parameter should be a JSONObject you do not need the getParams() method just pass them into the request.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
method,
url,
jsonObjParams, // <<< HERE
responseListener,
errorListener);
it happened because Volley params cache.
clean it like this
requestQueue.getCache().clear();
hope it's useful!😃
I solved my issue by simply removing Content-Type from header :)
Please override the getBody() method, and if your server can not handle JSON request parameter, you have to override the getHeaders() method to change your Content-Type.
Issue can found here: https://github.com/mcxiaoke/android-volley/issues/82
For JSONobjectRequest the getParams() doesn’t work for POST requests so you have to make a customRequest and override getParams() method over there. Its because JsonObjectRequest is extended JsonRequest which overrides getBody() method directly, so your getParam() would never invoke. To invoke your getParams() method you first have to override getBody(). Or for a simple solution you can use StringRequest.
Try using shouldCache(false) for your request object before you add it into queue.
To provide POST parameter build a JSONObject with your POST parameters and pass that JSONObject as a 3rd parameter. JsonObjectRequest constructor accepts a JSONObject in constructor which is used in Request Body.
JSONObject paramJson = new JSONObject();
paramJson.put("key1", "value1");
paramJson.put("key2", "value2");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url,paramJson,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
I had the same problem
I solved it using clear queue Cache
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.getCache().clear();
requestQueue.add(stringRequest);
just use requestQue.getCache().clear();
If you do a Post using Android Volley, it should call the methods getHeaders(), getBody(), getParams(), and getBodyContentType() in that order.
If you do a GET request using Android Volley, it should call the methods getHeaders() only.
if you use My Singleton try this:
MyVolley.getInstance(this).getRequestQueue().getCache().clear();
Maybe you use cache on your code

Categories

Resources