JSON请求始终返回null

时间:2017-11-21 20:42:58

标签: php android mysql json

我正在尝试让我的Android项目与LAMP服务器一起工作,但JSON请求继续返回null。 LAMP服务器工作正常,我的请求是到达它上面的php文件。

这是我的代码:

class GetEntryData extends AsyncTask<String, String, String> {

private static JSONParser jsonParser;
private List<NameValuePair> entry_data;

private static String server_address;
private static String server_db;
private static String db_table;
private static int id;
public static String TAG = "LogDebug";

private static final String TAG_SUCCESS = "success";

public  GetEntryData(String server_address, String server_db, String db_table, int id) {
    this.server_address = server_address;
    this.server_db = server_db;
    this.db_table = db_table;
    this.id = id;
}

@Override
protected String doInBackground(String[] params) {

    Log.d(TAG, "Sending JSON request");
    jsonParser = new JSONParser();
    int success;
        entry_data = new ArrayList<NameValuePair>();
        entry_data.add(new BasicNameValuePair("id", String.valueOf(id)));
        Log.d(TAG, "server address: " + server_address + "   enrty data: " + entry_data.toString());
        JSONObject json = jsonParser.makeHttpRequest(server_address, "GET", entry_data);
        try {
        Log.d(TAG, json.toString());

        success = json.getInt(TAG_SUCCESS);
        if (success == 1) {
            JSONArray productObj = json.getJSONArray(db_table);
            JSONObject entry = productObj.getJSONObject(0);
            return entry.toString();
        } else {
            return null;
        }
    } catch (NullPointerException e) {
        return e.getMessage();
    }catch (JSONException e){
            return e.getMessage();
        }
}
@Override
protected void onPostExecute(String result) {
    Log.d(TAG, "Entry data was written with the result: " + result);
}

}

我的JSON课程:

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {

}
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
    try {
        if(method == "POST"){
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    return jObj;

}}

我的php代码:

<?php

$response = array();

require 'db_connect.php';

$db = new DB_CONNECT();

if (isset($_GET["id"])) {
$pid = $_GET['id'];

$result = mysqli_query("SELECT *FROM marker_data WHERE id = $id");

if (!empty($result)) {
    if (mysqli_num_rows($result) > 0) {

        $result = mysqli_fetch_array($result);

        $entry = array();
        $entry["id"] = $result["id"];
        $entry["title"] = $result["title"];
        $entry["address"] = $result["address"];
        $entry["image"] = $result["image"];
        $entry["working_hours"] = $result["working_hours"];
        $entry["product_range"] = $result["product_range"];
        $entry["comments"] = $result["comments"];
        $entry["confirmation_status"] = $result["confirmation_status"];
        $entry["latitude"] = $result["product_range"];
        $entry["longitude"] = $result["longitude"];


        $response["entry"] = array();

        array_push($response["entry"], $entry);

        echo json_encode($response);
    } else {
        $response["success"] = 0;
        $response["message"] = "No entry found";

        echo json_encode($response);
    }
} else {
    $response["success"] = 0;
    $response["message"] = "No entry found";

    echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

echo json_encode($response);
}
?>

db_connect.php:

<?php

class DB_CONNECT {

function __construct() {
    $this->connect();
}

function __destruct() {
    $this->close();
}

function connect() {
    require 'db_config.php';

    $con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysqli_error());

    $db = mysqli_select_db(DB_DATABASE) or die(mysqli_error()) or die(mysqli_error());

    return $con;
}

function close() {
    mysqli_close();
}

}

?>

我在Logcat中获得的是: 解析数据时出错org.json.JSONException:字符0处的输入结束 使用结果写入条目数据:尝试调用虚方法&#39; java.lang.String org.json.JSONObject.toString()&#39;在空对象引用上

有一个id = 1的条目(我试图得到),并且所有变量名称(如服务器,数据库,php文件等)都已正确设置。

2 个答案:

答案 0 :(得分:1)

我的建议也是使用PDO

所以db_connect,可能是这样的:

<?php

try {
    $conn = new PDO("mysql:host=localhost;dbname=test;", 'root', 'test');
} catch (PDOException $e) {
    die("Error occurred: " . $e->getMessage());
}

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

header('Content-Type: text/html; charset=utf-8');

?>

getMarkerData.php

<?php

require 'DBConnect.php'; //PHP file for connect to database
header('Content-Type: application/json'); //You want answers in json 
$header = apache_request_headers(); //set headers

if (isset($header['authorization'])) { //if ID is posted than do stuffs

    $id = $header['authorization']; //save ID in some variable

    //You can put user id in marker_data table and then get values from there, but for easier testing you can firstly check if user ID is found in users table and if is not than just answer in json user not found
    $stmt = $conn->prepare("SELECT id FROM users WHERE id = :id");
    $stmt->bindParam(":id", $id);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($row < 1) {
        $error['success'] = 0; //Success is for easier handling on Android to know what to do next
        $error['message'] = 'Access denied!';

        die(json_encode($error));
    } else {
       //so user is found and we now want data for that user
        $sql = $conn->prepare("SELECT * FROM marker_data WHERE userid = :uid);
        $sql->bindParam(":uid", $id);
        $sql->execute();
        $data = $sql->fetch(PDO::FETCH_ASSOC);

        if ($data > 0) {
            //So here you choose which data you want to fetch
            $error['success'] = 1;
            $error['product_range'] = $data['product_range'];
            $error['working_hours'] = $data['working_hours'];

            echo json_encode($error);
        }

    }

} else {
    $error["success"] = 0;
    $error["message"] = "Access denied!";

    die(json_encode($error));
}

?>

对于android和JSON的例子

public class CheckingDatabase extends AsyncTask<String, Integer, Integer> {
        //Add your ID for identification
        public CheckingDatabase(String postID) {
            postID = id;
        }

        @Override
        protected Integer doInBackground(String... params) {

            try {
                //Objects of HttpClient and HttpPost
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost("http://localhost/PHPScripts/getMarkerData.php");
                HttpParams httpParams = new BasicHttpParams();
                int timeoutConnection = 5000;
                HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConnection);
                int timeoutSocket = 7000;
                HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket);
                httpPost.setHeader("authorization", id); //ID

                //Post request
                try {
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    InputStream inputStream = null;
                    inputStream = httpEntity.getContent();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    StringBuilder stringBuilder = new StringBuilder();

                    String line = null;
                    while ((line = bufferedReader.readLine()) != null) {
                        stringBuilder.append(line + "\n");
                    }
                    String result = null;
                    result = stringBuilder.toString();
                    json = result;
                } catch (ClientProtocolException cpe) {
                    cpe.printStackTrace();
                    Log.d("URIException", cpe.getMessage());
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                    Log.d("IOException", ioe.getMessage());
                }

                Thread.sleep(1000);
            } catch (InterruptedException ie) {
                ie.printStackTrace();
                Log.d("InterruptedException", ie.getMessage());
            }

            //JSON response
            try {
                JSONObject jsonObject = new JSONObject(json);
                success = jsonObject.getInt("success");

                if (success == 1) { //If success is 1 get data
                    product_range = jsonObject.getString("product_range");
                    working_hours = jsonObject.getString("working_hours");
                }
            } catch (JSONException je) { //Otherveis exception
                je.printStackTrace();
                Log.d("JSONException", je.getMessage());
            }

            return success;
        }

        @Override
        protected void onPostExecute(Integer integer) {
            integer = success;

            if (integer == 1) {
                checkForChanges(); //Now you can call some another method to do some other things with data or something else, or even you don't need this :D
            }
        }
    }

也许只是建议使用另一个随机生成的ID进行用户识别。而且,如果测试是否真的很好,你可以使用ARC(Chrome的扩展,测试可以)。

答案 1 :(得分:0)

你需要对有关sql注入的评论采取行动。使用PDO。

Nt足够的信息可以完全帮助您。错误的行号有助于甚至完整的logcat输出。

您可以尝试从您的php返回一些有效的json。这可以防止错误,你可以确定PHP代码返回你期望的。一旦你开心,你可以把json放回你需要的样子 - 也许自己格式化它而不是依赖关联数组的json_encode()。