Volley and Gson -Sending a POST request using JSONObjectRequest

别说谁变了你拦得住时间么 提交于 2019-12-11 12:52:51

问题


I'm new here and I don't very well speak English, but I do my best to explain me. I have some problems with the Post request. This is my code:

private void makeRequest() {
    String url = "http://diegocardenas.netau.net/comprobar_usuario.php";


    JsonObjectRequest request1=new JsonObjectRequest(Method.POST, url, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            onConnectionFinished();
            Usuario usuario = new Gson().fromJson(response.toString(), Usuario.class);
            if (usuario != null) {
                Log.i("App1", "Nombre:" + usuario.getNombre() + " Correo: " + usuario.getCorreo());
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            onConnectionFailed(error.toString());
            Log.i("App1", error.getMessage());
        }
    }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> params=new HashMap<>();
            params.put("correo","daniel@gmail.com");
            params.put("clave","daniel");
            return params;
        }
    };
    addToQueue(request1);
}

This is the Usuario class:

public class Usuario {
    private int cod_usuario, contador, estado;
    private String nombre, correo;

    public Usuario() {
    }

    public int getCod_usuario() {
        return cod_usuario;
    }

    public void setCod_usuario(int cod_usuario) {
        this.cod_usuario = cod_usuario;
    }

    public int getContador() {
        return contador;
    }

    public void setContador(int contador) {
        this.contador = contador;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public String getCorreo() {
        return correo;
    }

    public void setCorreo(String correo) {
        this.correo = correo;
    }

    public int getEstado() {
        return estado;
    }

    public void setEstado(int estado) {
        this.estado = estado;
    }
}

and my PHP... sorry but I'm a beginner in PHP

comprobar_usuario.php

<?php
header('Content-Type: text/html; charset=UTF-8');
include_once('usuario.class.php');
$usuario=new Usuario();
$correo=$_POST['correo'];
$clave=$_POST['clave'];
echo json_encode($usuario->getJSONUsuario($correo,$clave));
?>

usuario.class.php

<?php
include_once('database.class.php');
class Usuario{
public function getJSONUsuario($correo,$clave){
        $json= array();
        $result=$this->comprobarUsuario($correo,$clave);
        if(mysql_num_rows($result)){
            while ($row=mysql_fetch_row($result)) {
                $json[]=array('nombre'=>$row[1], 'correo'=>$row[2],
                    'contador'=>$row[5]);
            }
        }
        return $json;
}
    private function comprobarUsuario($correo, $clave){
        $consulta="SELECT * FROM usuario WHERE correo='".$correo."' 
            AND clave='".$clave."'";
        $db=new Database();
        return $db->ejecutarConsulta($consulta);
    }
}
?>

database.class.php

<?php
include_once('datos_conexion.class.php');

class Database{

    public function ejecutarConsulta($consulta){
        $conexion=mysql_connect(DatosConexion::getServidor(), DatosConexion::getUsuarioConexion(),
            DatosConexion::getClaveConexion());
        mysql_set_charset('utf8',$conexion);
        if(!$conexion){
            die('No se pudo conectar al servidor: '.mysql_error());
        }else{
            mysql_select_db(DatosConexion::getDataBase(),$conexion);
            $resultado=mysql_query($consulta);
            mysql_close();
            return $resultado;
        }
    }
}
?>

the table: Usuario fields: cod_usuario Int, nombre Varchar, correo Varchar, clave Varchar, estado Boolean, contador Int

EDITED The Log:

05-28 09:52:02.921 10862-11210/com.diego.app1I/qtaguid﹕ Failed write_ctrl(u 67) res=-1 errno=22 
05-28 09:52:02.921 10862-11210/com.diego.app1I/qtaguid﹕ Untagging socket 67 failed errno=-22 
05-28 09:52:02.921 10862-11210/com.diego.app1W/NetworkManagementSocketTagger﹕ untagSocket(67) failed with errno -22 
05-28 09:52:02.921 10862-10862/com.diego.app1 I/App1﹕ org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject

I prove the connection using GET and I returned the data, but when using POST failure all xD I think the problem is the method getparams...

Help Please!!!!


回答1:


if you think the problem is with getParams, then with Volley you don't have to use the getParams, it knows how to deal with JSONObject so you can use:

  String someurl = URL;

    Map<String, Object> jsonParams = new HashMap<>();
    jsonParams.put("someparam", getSomeParam());

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, someurl, new JSONObject(jsonParams),
            new Response.Listener<JSONObject>()
            {
                @Override
                public void onResponse(JSONObject response)
                {
                    Log.d(TAG + ": ", "Response: " + response.toString());
                    //do other stuff 
                }
            },
            new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error)
                {
                    if (null != error.networkResponse)
                    {
                        Log.d(TAG + ": ", "Error Response code: " + error.networkResponse.statusCode);
                    }
                }
            });

    requestQueue.add(request);

Also - make sure the variable names in Usuario class match the names you get back in your Json, if it doesn't match the variable in Usuario will be NULL by default.



来源:https://stackoverflow.com/questions/30496511/volley-and-gson-sending-a-post-request-using-jsonobjectrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!