Volley Not Calling Getparams() for Standard Post Request

Volley not calling getParams() for standard POST request

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

Android volley does not calling getParams in POST request

Finally, I figured it. The problem was in setDonorsList() method. I have hard coded the condition while(count < 10). This produces a JSON exception called "index out of range" since my DB doesn't have 10 entries. I changed the value like while(count < jsonArray.length()). Now everything is perfect. Guys thank you so much for your time and concern.

Volley does not call getParams for my custom request?

getParams() is not called on the GET method, so it seems you'll have to add it to the URL before you send the request.

Check out the JavaDoc:

Returns a Map of parameters to be used for a POST or PUT request.

Can throw {@link AuthFailureError} as authentication may be required
to provide these values.

Note that you can directly override {@link #getBody()} for custom
data.

@throws AuthFailureError in the event of auth failure

Android Volley getParams() method not getting called for JsonObjectRequest

use this Custom volley request class

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Map;

public class CustomJsonRequest extends Request<JSONObject> {

private Listener<JSONObject> listener;
private Map<String, String> params;

public CustomJsonRequest(String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = reponseListener;
this.params = params;
}

public CustomJsonRequest(int method, String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}

@Override
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
return params;
}

;

@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}

@Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
}

you can use it with

Map<String,String> params = new Hashtable<String, String>();

params.put("Email", mEmail.getText().toString().trim());
params.put("Username",mUsername.getText().toString().trim());
params.put("Password",mPassword.getText().toString().trim());
params.put("BirthDay",mBirthday.getText().toString().replaceAll("\\s","-"));
params.put("Sex",SelectedRadio());
params.put("Bitmap",getEncodedBitmap());

CustomJsonRequest request = new CustomJsonRequest(Request.Method.POST, url, params,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {

}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

}
});

request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().getRequestQueue().add(request);

Actually this a issue with sending parameters with volley. Check this answer
https://stackoverflow.com/a/27091088/1320616

EDIT: Explanation for this behaviour

your JsonObjectRequest class extends from JsonRequest which extends from Request.

inside your Request class there is a method

/**
* Returns the raw POST or PUT body to be sent.
*
* <p>By default, the body consists of the request parameters in
* application/x-www-form-urlencoded format. When overriding this method, consider overriding
* {@link #getBodyContentType()} as well to match the new body format.
*
* @throws AuthFailureError in the event of auth failure
*/
public byte[] getBody() throws AuthFailureError {
Map<String, String> params = getParams();
if (params != null && params.size() > 0) {
return encodeParameters(params, getParamsEncoding());
}
return null;
}

notice that this method is calling getParams() method. It is the same method that you are overriding while making the call.

But if you look inside JsonRequest class, there is a method

@Override
public byte[] getBody() {
try {
return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET);
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
mRequestBody, PROTOCOL_CHARSET);
return null;
}
}

it means the getBody() of Request has been overridden by getBody() of JsonRequest class which means your getParams() will never get called. So you need a custom class which directly extends Request class and doesn't override the getBody() method of Request class.

Volley request not taking parameters

This answer assumes you are trying to make a GET request.

I had a similar issue. GET requests are a little different than POST when it comes to passing parameters when using Volley.
when you make a GET request, ONE of the WAYS to pass the params is inside the url string itself, this worked for me :

(this is a partial example, but should give you most of what you need to modify your own code)

In the class that sends the requests I used a small method to append the params to the url:

//this method sits somewhere in your class
private String createGetWithParams(String url, Map<String, Object> params)
{
StringBuilder builder = new StringBuilder();
for (String key : params.keySet())
{
Object value = params.get(key);
if (value != null)
{
try
{
value = URLEncoder.encode(String.valueOf(value), HTTP.UTF_8);
if (builder.length() > 0)
builder.append("&");
builder.append(key).append("=").append(value);
}
catch (UnsupportedEncodingException e)
{
}
}
}

return (url += "?" + builder.toString());
}

//this method sits somewhere in the same class, this fires the request
public void doSomeRequest()
{
Map<String, Object> jsonParams = new HashMap<>();
jsonParams.put("SomeParam", SomeParamValue);
jsonParams.put("SomeOtherParam", SomeOtherParamValue);

String url = createGetWithParams("some/request/url", jsonParams);

StringRequest request = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>()
{
@Override
public void onResponse(String response)
{
// do whatever
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
if (null != error.networkResponse)
{
Log.d(" Volley Error Response code: ", ""+ error.networkResponse.statusCode);
}
}
});

requestQueue.add(request);

I Also created a custom request class that replaced the StringRequest, but that was to have more control over parsing the response - might help you though, in this class I only override the response:

public class CustomStringRequest extends StringRequest
{
private final Response.Listener<String> mListener;

public CustomStringRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener)
{
super(method,url, listener, errorListener);
mListener = listener;
}

@Override
protected Response<String> parseNetworkResponse(NetworkResponse response)
{
try
{
// response.data is the byte array, do whatever..
String responseBody = new String(response.data, "utf-8");
Log.d(" NetworkResponse", responseBody);

return (Response.success(responseBody, getCacheEntry()));
}
catch (UnsupportedEncodingException e)
{
VolleyLog.e("UnsupportedEncodingException");
Log.d("NetworkResponse Exception", e.getMessage() );
return (null);
}
}

@Override
protected void deliverResponse(String response)
{
mListener.onResponse(response);
}

}

the other way I know of is using a specific http client, I haven't used that way, but you could probably use OkHttp, or something similar.

Hope this helps!

Volley JsonObjectRequest Post parameters no longer work

I ended up using Volley's StringRequest instead, because I was using too much valuable time trying to make JsonObjectRequest work.

RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://myserveraddress";

StringRequest strRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
@Override
public void onResponse(String response)
{
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "test");
return params;
}
};

queue.add(strRequest);

This worked for me. Its just as simple as JsonObjectRequest, but uses a String instead.

Google Volley ignores POST-Parameter

EDIT:

I deleted my previous answer since it wasn't accurate.

I'll go over what I know today:
Apparently, getParams should work. But it doesn't always.
I have debugged it myself, and it seems that it is being called when performing a PUT or POST request, and the params provided in that method are in a regular GET parameters string (?param1=value1¶m2=value2...) and encoded and put in the body.

I don't know why but for some reason this doesn't work for some servers.

The best alternate way I know to send parameters, is to put your parameters in a JSONObject and encode its contents in the request's body, using the request constructor.



Related Topics



Leave a reply



Submit