how to send post request with data in Volley? - android

This is my android code
JSONObject params = new JSONObject();
params.put("username","rajesh#gmail.com");
params.put("password","hellothere");
JsonObjectRequest loginRequest = new JsonObjectRequest(
Request.Method.POST,
"http://192.168.2.67/tmp/test.php",
params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.d("","");
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d("","");
}
});
requestQueue.add(loginRequest);
The server code in php
<?php
$usr = $_REQUEST['username'];
$pwd = $_REQUEST['password'];
$resp[$usr]=$pwd;
echo json_encode($resp);
?>
the response i'm getting is
{"":null}
I tried with apache http cleint and it worked prferectly
is there any way i can do this with volley?

To send parameters in request body you need to override either
getParams() or getBody() method of the request classes
Source: Asynchronous HTTP Requests in Android Using Volley

#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("username", "SomeUser");
params.put("password", "blabla");
return params;
}
This is the way you should override getParams() method.

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.

Post Method using Volley not working

Hi i am using Volley for my login page. I need to pass data like this manner
{
userID : '-988682425884628921',
email :'aditya#vyas.com',
passwd : '123ss'
}
I am using POST Method to send data,I already check in DHC, The Api is working fine in DHC and I am getting JSON Response, But when i try with Volley i am not able to get response. and not even any error in my logcat.
JAVA code
RequestQueue mVolleyQueue = Volley.newRequestQueue(this);
CustomRequest req = new CustomRequest(Request.Method.POST,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.v("tag","login response " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v("tag","login error response " + error.getMessage());
}
}){
#Override
public Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("userID", "-988682425884628921");
params.put("email", "aditya#vyas.com");
params.put("passwd", "123ss");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
mVolleyQueue.add(req);
Error
05-28 09:20:14.696 2450-2468/com.android.msahakyan.expandablenavigationdrawer E/tag﹕ parseNetworkError is ! null
05-28 09:20:14.697 2450-2468/com.android.msahakyan.expandablenavigationdrawer E/tag﹕ parseNetworkError status code : 400
05-28 09:20:14.697 2450-2468/com.android.msahakyan.expandablenavigationdrawer E/tag﹕ parseNetworkError message : <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Header</h2>
<hr><p>HTTP Error 400. The request has an invalid header name.</p>
</BODY></HTML>
}
Solved your problem. Just used JsonArrayRequest and passed parameters in JsonObject form:
Map<String, String> params = new HashMap<String, String>();
params.put("userID", "userid");
params.put("email","email");
params.put("passwd", "password");
JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST, "url", new JSONObject(params),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
System.out.println("response -->> " + response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("change Pass response -->> " + error.toString());
}
});
request.setRetryPolicy(new
DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(activity).add(request);
No need of overriding getParams() or getHeaders().
Problem : 1
You were getting response code 500 because the server was accepting the params as JsonObject and we are trying to feed String.
Problem : 2
You were using JsonObjectRequet but the response from the server was in JsonArray so you need to use JsonArrayRequest to accept the response in JsonArray
Try and let me know this helps or not :)
I had a similar problem. I had overwritten the Content-Type in the getHeaders Method:
headers.put("Content-Type", "application/json; charset=UTF-8");
but Volley itself added a Content-Type parameter, so there were two of those parameters. Delete the line had solved my Problem.
You need to override protected Map<String, String> getParams() to pass parameters in POST.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Login Response", response.toString());
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.getStackTrace());
VolleyLog.d("ErrorVolley", "Error: " + error.getStackTrace());
hidepDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("userID", "2"));
params.put("email","aa#a.kl");
params.put("passwd", "ddddd");
return params;
}
};
Beware of content-type header. Volley handles it differently from other headers and it's not shown in Map<> Headers. Instead of overriding getHeaders() method to set content-type, you should override getBodyContentType() like this:
#Override
public String getBodyContentType()
{
return "application/json; charset=utf-8";
}
i have same problem use this :
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(LoginActivity.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getParams() {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
headers.put("UN", UserName);
headers.put("PW", PassWord);
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
Just need to add headers.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); to parms
good luck.

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/

Volley Post JsonObjectRequest ignoring parameters while using getHeader and getParams

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

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