【问题标题】:Android JSON request, Inputstream returning nullAndroid JSON请求,输入流返回null
【发布时间】:2017-11-26 14:32:57
【问题描述】:

我有一个带有 register.php 的网站(在 localhost 上运行)。 网站中的代码(AJAX jQuery)返回一个 JSON 数组,现在一切正常。 Android 中的代码在我需要数组时返回 null。

代码:

HttpURLConnection urlConnection;
StringBuilder result = new StringBuilder();
DataOutputStream dataOutputStream;
try {
    URL url = parmeters[0].url;
    String username = parmeters[0].username;
    String email = parmeters[0].email;
    String password = parmeters[0].password;
    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setConnectTimeout(5000);
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty("Accept", "application/json");
    urlConnection.setRequestProperty("Content-Type", "application/json");
    urlConnection.connect();
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("username", username);
    jsonObj.put("email", email);
    jsonObj.put("password", password);
    dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
    dataOutputStream.writeBytes(URLEncoder.encode(jsonObj.toString(), "UTF-8"));
    dataOutputStream.flush();
    dataOutputStream.close();
    int responsecode = urlConnection.getResponseCode();
    Log.w("OnStart", "doInBackground: " + responsecode);
    if (responsecode == 200 || responsecode == 201) {
        InputStream input = urlConnection.getInputStream();
        Scanner s = new Scanner(input).useDelimiter("\\A");
        result.append(s.hasNext() ? s.next() : "");
        }
    urlConnection.disconnect();
} catch (IOException | JSONException e) {
    Log.e("OnStart", e.toString());
}
Log.w("OnStart", result.toString());
return result.toString();

堆栈跟踪:

06-23 05:46:16.381 22500-22536/com.newworldgrip.lostandfound.lostandfound D/EGL_emulation: eglMakeCurrent: 0xa2d79580: ver 2 0 (tinfo 0xaed0b350) 06-23 05:46:20.046 22500-22506/com.newworldgrip.lostandfound.lostandfound I/zygote:做 部分代码缓存收集,代码=28KB,数据=30KB 06-23 05:46:20.048 22500-22506/com.newworldgrip.lostandfound.lostandfound I/zygote:之后 代码缓存集合,代码=28KB,数据=30KB 06-23 05:46:20.048 22500-22506/com.newworldgrip.lostandfound.lostandfound I/zygote: 将代码缓存容量增加到 128KB 06-23 05:46:20.715 22500-22506/com.newworldgrip.lostandfound.lostandfound I/zygote:做 部分代码缓存收集,代码=61KB,数据=53KB 06-23 05:46:20.716 22500-22506/com.newworldgrip.lostandfound.lostandfound I/zygote:之后 代码缓存集合,代码=61KB,数据=53KB 06-23 05:46:20.716 22500-22506/com.newworldgrip.lostandfound.lostandfound I/zygote: 将代码缓存容量增加到 256KB 06-23 05:46:22.452 22500-22506/com.newworldgrip.lostandfound.lostandfound I/zygote:做 完整的代码缓存集合,代码=123KB,数据=100KB 06-23 05:46:22.452 22500-22506/com.newworldgrip.lostandfound.lostandfound I/zygote:之后 代码缓存集合,代码=116KB,数据=73KB 06-23 05:46:23.648 22500-22506/com.newworldgrip.lostandfound.lostandfound I/zygote:做 部分代码缓存收集,代码=122KB,数据=84KB 06-23 05:46:23.648 22500-22506/com.newworldgrip.lostandfound.lostandfound i/zygote:代码缓存收集后,code=122KB,data=84KB 06-23 05:46:23.648 22500-22506/com.newworldgrip.lostandfound.lostandfound I/zygote:将代码缓存容量增加到 512KB 06-23 05:46:29.721 22500-22537/com.newworldgrip.lostandfound.lostandfound D/NetworkSecurityConfig:未指定网络安全配置,使用 平台默认 06-23 05:46:29.737 22500-22506/com.newworldgrip.lostandfound.lostandfound I/zygote:做 完整的代码缓存集合,代码=208KB,数据=162KB 06-23 05:46:29.737 22500-22506/com.newworldgrip.lostandfound.lostandfound I/zygote:之后 代码缓存集合,代码=205KB,数据=134KB 06-23 05:46:29.742 22500-22537/com.newworldgrip.lostandfound.lostandfound W/OnStart: 做背景:200 06-23 05:46:29.763 22500-22536/com.newworldgrip.lostandfound.lostandfound D/EGL_emulation: eglMakeCurrent: 0xa2d79580: ver 2 0 (tinfo 0xaed0b350) 06-23 05:46:29.784 22500-22536/com.newworldgrip.lostandfound.lostandfound D/EGL_emulation: eglMakeCurrent: 0xa2d79580: ver 2 0 (tinfo 0xaed0b350) 06-23 05:46:29.828 22500-22536/com.newworldgrip.lostandfound.lostandfound D/EGL_emulation: eglMakeCurrent: 0xa2d79580: ver 2 0 (tinfo 0xaed0b350) 06-23 05:47:03.396 22500-22506/com.newworldgrip.lostandfound.lostandfound I/zygote:做 部分代码缓存收集,代码=245KB,数据=173KB 06-23 05:47:03.396 22500-22506/com.newworldgrip.lostandfound.lostandfound i/zygote:代码缓存收集后,code=245KB,data=173KB 06-23 05:47:03.396 22500-22506/com.newworldgrip.lostandfound.lostandfound I/zygote:将代码缓存容量增加到 1024KB

注册.php:

<?php
/**
 * Created by PhpStorm.
 * User: Oded Shapira
 * Date: 6/2/2017
 * Time: 1:02 PM
 */
require_once "handler.php";
$db = new DataBaseHandler();
$returned = array("error" => FALSE);

if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['email'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $email = $_POST['email'];


    $result = $db->storeInDb($username, $email, $password);
    if ($result["error"]) {
        $returned["error"] = TRUE;
        $returned["error_msg"] = $result["error_msg"];
        echo json_encode($returned);
    } else {
        $returned["error"] = FALSE;
        $returned["user"] = $result;
        echo json_encode($returned);
    }

} else {
    $returned["error"] = TRUE;
    $returned["error_msg"] = "missing parameters";
    json_encode($returned);
}
?>

handler.php:

<?php
/**
 * Created by PhpStorm.
 * User: Oded Shapira
 * Date: 6/14/2017
 * Time: 3:41 PM
 */
class DB_Connect {
    private $conn;

    public function connect(){
        require_once 'include/Config.php';

        $this->conn = new mysqli(HOST,USER, PASS, DATABASE);
        if (!mysqli_connect_errno()){
            return $this->conn;
        } else {
            die("Sql error: " . $this->conn->error);
        }
    }
}

class DataBaseHandler {
    private $conn;

    function __construct()
    {
        $db = new DB_connect();
        $this->conn = $db->connect();
    }

    function __destruct()
    {
        if ($this->conn != null) {
            $this->conn->close();
        }
    }

    public function storeInDb($username, $email, $password) {
        $encrypted = md5($password);
        if ($this->checkExistence($email)) {
            return array("error"=>true, "error_msg"=>"Account with the same email exists.");
        } else {
            $result = $this->conn->prepare("INSERT INTO accounts (username, password, email) VALUES 
                                      (?, ?, ?)");
            if ($result === false){
                die("mysqli error: " . $this->conn->error);
            } else {
                $result->bind_param("sss", $username, $encrypted, $email);
                $result->execute();
                $result->close();
                $user["error"] = false;
                return $user;
            }
        }
    }

    public function getUser($email,$password) {
        $encrypted = md5($password);
        if ($this->checkExistence($email)) {
            $stmt = $this->conn->prepare("SELECT * FROM accounts WHERE email = ?");
            if ($stmt === false) {
                return array("error"=>true, "error_msg"=>"unknown error while fetching from database");
            } else {
                $stmt->bind_param("s", $email);
                $stmt->execute();
                $user = array();
                $stmt->bind_result($user["id"], $user["username"], $user["password"], $user["email"], $user["created_at"], $user["updated_at"]);
                if ($stmt->fetch()) {
                    $pass = $user["password"];
                    $user["error"] = false;
                    if ($pass == $encrypted) {
                        $stmt->close();
                        return $user;
                    } else {
                        $stmt->close();
                        return array("error" => true, "error_msg" => "password does not match the one on the database , $encrypted" . $user["username"]);
                    }
                } else {
                    return array("error"=>true, "error_msg"=>"unknown error while fetching");
                }
            }
        } else {
            return array("error"=>true, "error_msg"=>"user does not exists");
        }
    }

    public function checkExistence($email) {
        $stmt = $this->conn->prepare("SELECT * FROM accounts WHERE email = ?");
        if ($stmt === false) {
            die("Mysqli error ". $this->conn->error);
        } else {
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $stmt->store_result();
            if($stmt->num_rows > 0) {
                $stmt->close();
                return true;
            } else {
                $stmt->close();
                return false;
        }
        }
    }
}
?>

【问题讨论】:

  • 您的堆栈跟踪根本不包含错误!
  • 建议您不要使用样板代码进行网络操作,而是使用强大的库,例如 OkHttpVolley
  • 使用 php 原生输入阅读器读取您的输入,例如 $postdata = file_get_contents('php://input');
  • 我实在看不懂Okhttp的语法。

标签: php android json


【解决方案1】:

我决定搬到火力基地! 它为我做了这些事情,我对它百分百满意。

【讨论】:

    猜你喜欢
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    相关资源
    最近更新 更多