Volley JsonObjectRequest Post request no funciona
Estoy usando android Volley para hacer una solicitud. Así que uso este código. No entiendo una cosa. Compruebo en mi servidor que params es siempre null. Considero que getParams() no funciona. ¿Qué debo hacer para resolver este problema?
RequestQueue queue = MyVolley.getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,SPHERE_URL,null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
System.out.println(response);
hideProgressDialog();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
hideProgressDialog();
}
}) {
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("id","1");
params.put("name", "myname");
return params;
};
};
queue.add(jsObjRequest);
7 answers
Intenta usar esta clase auxiliar
import java.io.UnsupportedEncodingException;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
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;
public class CustomRequest extends Request<JSONObject> {
private Listener<JSONObject> listener;
private Map<String, String> params;
public CustomRequest(String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
public CustomRequest(int method, String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
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);
}
}
En actividad/fragmento use esto
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
CustomRequest jsObjRequest = new CustomRequest(Method.POST, url, params, this.createRequestSuccessListener(), this.createRequestErrorListener());
requestQueue.add(jsObjRequest);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-23 18:12:43
Puede crear un JSONObjectReuqest
personalizado y anular el método getParams
, o puede proporcionarlos en el constructor como JSONObject
para ponerlos en el cuerpo de la solicitud.
Así (edité tu código):
JSONObject obj = new JSONObject();
obj.put("id", "1");
obj.put("name", "myname");
RequestQueue queue = MyVolley.getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,SPHERE_URL,obj,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
System.out.println(response);
hideProgressDialog();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
hideProgressDialog();
}
});
queue.add(jsObjRequest);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-07 15:24:05
Fácil para mí ! Lo conseguí hace unas semanas:
Esto va en el método getBody()
, no en getParams()
para una solicitud post.
Aquí está el mío:
@Override
/**
* Returns the raw POST or PUT body to be sent.
*
* @throws AuthFailureError in the event of auth failure
*/
public byte[] getBody() throws AuthFailureError {
// Map<String, String> params = getParams();
Map<String, String> params = new HashMap<String, String>();
params.put("id","1");
params.put("name", "myname");
if (params != null && params.size() > 0) {
return encodeParameters(params, getParamsEncoding());
}
return null;
}
(Asumí que quieres publicar los parámetros que escribiste en tu getParams)
Le di los parámetros a la petición dentro del constructor, pero como estás creando la petición sobre la marcha, puedes codificarlos dentro de tu override del método getBody ().
Este es el aspecto de mi código:
Bundle param = new Bundle();
param.putString(HttpUtils.HTTP_CALL_TAG_KEY, tag);
param.putString(HttpUtils.HTTP_CALL_PATH_KEY, url);
param.putString(HttpUtils.HTTP_CALL_PARAM_KEY, params);
switch (type) {
case RequestType.POST:
param.putInt(HttpUtils.HTTP_CALL_TYPE_KEY, RequestType.POST);
SCMainActivity.mRequestQueue.add(new SCRequestPOST(Method.POST, url, this, tag, receiver, params));
Y si quieres aún más esta última cadena params viene de:
param = JsonUtils.XWWWUrlEncoder.encode(new JSONObject(paramasJObj)).toString();
Y el paramasJObj es algo así : {"id"="1","name"="myname"}
la cadena JSON habitual.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-07 15:23:35
Cuando trabaja con JSONObject request necesita pasar los parámetros justo después de pasar el enlace en la inicialización, eche un vistazo a este código:
HashMap<String, String> params = new HashMap<>();
params.put("user", "something" );
params.put("some_params", "something" );
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, "request_URL", new JSONObject(params), new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// Some code
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//handle errors
}
});
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-17 13:02:05
Todo lo que necesita hacer es sobrescribir el método getParams en la clase Request. Tuve el mismo problema y busqué a través de las respuestas, pero no pude encontrar una adecuada. El problema es a diferencia de get request, los parámetros post que son redirigidos por los servidores pueden ser eliminados. Por ejemplo, lea esto . Por lo tanto, no arriesgue sus solicitudes para ser redirigido por el servidor web. Si estás apuntando http://example/myapp , luego mencione la dirección exacta de su servicio, es decir http://example.com/myapp/index.php .
Volley está bien y funciona perfectamente, el problema proviene de otro lugar.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:26
La función de anulación getParams funciona bien. Se utiliza el método POST y se ha establecido el jBody como null. Por eso no funciona. Puede usar el método GET si desea enviar jBody null. Tengo override el método getParams y funciona bien con el método GET (y null jBody) bien con el método POST (y jBody != null)
También hay todos los ejemplos aquí
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-16 11:49:04
Tuve el mismo problema una vez, el array POST vacío es causado debido a una redirección de la solicitud (en el lado del servidor), arregla la URL para que no tenga que ser redirigida cuando llegue al servidor. Por ejemplo, si https es forzado usando el .archivo htaccess en su aplicación del lado del servidor, asegúrese de que su solicitud de cliente tenga el prefijo "https://". Por lo general, cuando ocurre una redirección, el array POST se pierde. Espero que esto ayude!
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-17 09:57:23