凌空GSON - 发送使用JSONObjectRequest POST请求 [英] Volley and Gson -Sending a POST request using JSONObjectRequest

查看:499
本文介绍了凌空GSON - 发送使用JSONObjectRequest POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的,我不很好说英语,但我尽我所能来解释我。
我有一些问题与POST请求。这是我的code:

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

这是Usuario类:

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

和我的PHP ...很抱歉,但我在PHP初学者

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

comprobar_usuario.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

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

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;
        }
    }
}
?>

表:Usuario
字段:cod_usuario诠释,农布雷VARCHAR,则邮报varchar,将釜VARCHAR,则埃斯塔布尔,康塔多诠释

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

EDITED
日志:

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

我证明使用GET的连接,我返回的数据,但使用POST失败所有的xD时
我认为这个问题是方法getParams ...

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...

请帮助!!!!

推荐答案

如果您认为问题是getParams,然后用排枪,你不必使用getParams,它知道如何处理的JSONObject所以你可以使用

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

另外 - 确保在Usuario类中的变量名匹配您取回您的JSON的名字,如果它不匹配Usuario变量将默认为NULL

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.

这篇关于凌空GSON - 发送使用JSONObjectRequest POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆