2
I am trying to make a POST request with Volley Android, but my Webservice does not recognize the json file that is sent as parameter. With the Google Chrome Postman plugin Webservice consumes perfectly without problems.
Below is my method that uses json in Webservice:
@POST
@Path("/login")
@Consumes("application/json")
@Produces("application/json")
public Response authenticate(Usuario usuario) {
try{
System.out.println("CPF: " + usuario.getCpfUsuario());
return Response.ok("OK").build();
} catch (Exception e) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
}
My Android client:
Usuario u = new Usuario("sadsadsad","asdaddad");
Gson gson = new Gson();
String s = new String(gson.toJson(u));
Map<String, String> params = new HashMap<String, String>();
params.put("Usuario", s);
JsonObjectRequest mCustomRequest = new JsonObjectRequest(
Request.Method.POST,
"http://(meuip):8080/webservice/authentication/login",
new JSONObject(params),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
mTextView.setText("Retorno: " + response);
}
},
new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("Falhou: " + error);
Log.i("SAIDA: ", "" + error);
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json; charset=utf-8");
return headers;
}
};
NetworkConnection.getInstance(getActivity()).addRequestQueue(mCustomRequest);
The output in Webservice when accessed with Android client is CPF: null and with Postman CPF: "the value passed"
The android client response is: com.android.Volley.Authfailureerror
In Postman, Voce puts the parameters as a JSON? Some error occurs on the server?
– Thiago Luiz Domacoski
An example of how to pass the parameter in Postman: {"activeUsuario":false,"cpfUsuario":"11111111111","idDeptoUsuario":0,"numeroUsuario":0,"senhaUsuario":"5efe56928251a83b29af558c258e0c50"}
– Pedro A.
If you pass a JSON on Postman, compare if there is a difference between it and what is generated by Android!
– Thiago Luiz Domacoski
Generates exactly the same.
– Pedro A.
Try to pass this way: new Jsonobject("{"activoUsuario":false,"cpfUsuario":"11111111111","idDeptoUsuario":0,"numeroUsuar u200C io":0,"senhaUsuario":"5efe56928251a83b29af558c258e0c50"} ")
– Thiago Luiz Domacoski
I copied it just like it passed me the indentation problem... Any suggestions ?
– Pedro A.
Check this post: http://stackoverflow.com/questions/23220695/google-volley-how-to-send-a-post-request-with-json-data
– Thiago Luiz Domacoski
So I did the same example of this link and the same thing happens, I think the json that is coming to the webservice is not compatible.
– Pedro A.
#Thiago Luiz Domacoski, I implemented the solution below. I was transforming the Object into a String.
– Pedro A.