无法从Android代码向PHP发送参数

时间:2015-06-17 18:20:05

标签: php android mysql

我正在尝试开发一个简单的Android应用程序,我将用户的信息存储到服务器上。所以我开发了我的应用程序的前端,我在我的服务器上创建了一个MySql数据库。我编写了更新数据库所需的PHP脚本,我在Android代码中编写了一个解析器来解析并将数据发送到服务器。

问题是,我无法将Android代码中的参数发送到我的PHP代码。我在SO和许多其他论坛上阅读了很多问题和答案,但似乎没有什么对我有用。请帮忙。

我创建了一个ASync Task,它执行将数据发送到服务器的任务。这是异步任务的代码。

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

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    // Creating user
    protected String doInBackground(String... args) {
        String name = user.getName();
        String firstname = user.getFirstName();
        String lastname = user.getLastName();
        String number = user.getNumber();
        String email = user.getEmail();
        String status = user.getStatus();
        String dob = user.getDob();

        // Building Parameters
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("name", name));
        params.add(new BasicNameValuePair("firstname", firstname));
        params.add(new BasicNameValuePair("number", number));
        params.add(new BasicNameValuePair("lastname", lastname));
        params.add(new BasicNameValuePair("email", email));
        params.add(new BasicNameValuePair("status", status));
        params.add(new BasicNameValuePair("dob", dob));

        JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                "POST", params);

        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
            } else {
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
    protected void onPostExecute(String file_url) {
    }
}

上面代码中的'url_create_product'是我服务器的PHP创建用户文件的URL,我稍后也会包含该文件。

接下来是我的JSONParser文件。

package com.osahub.rachit.osachatting.server;

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * Created by Rachit on 13-06-2015.
 */
public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
                                      List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if (method == "POST") {
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                /*HttpParams httpParams = httpClient.getParams();
                HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
                HttpConnectionParams.setSoTimeout(httpParams, 10000);*/
                HttpPost httpPost = new HttpPost(url);
                UrlEncodedFormEntity urlEncoded = new UrlEncodedFormEntity(params, "UTF-8");
                httpPost.setEntity(urlEncoded);

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

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

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

        } 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 parse the string to a JSON object
        try {
            jObj = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

最后,我的create_user.php文件位于下方。

create_user.php
<?php


$response = array();

// check for required fields
if (isset($_POST['number'])) {

    $name = $_POST['name'];
    $first_name = $_POST['first_name'];
    $number = $_POST['number'];
    $last_name = $_POST['last_name'];
    $email = $_POST['email'];
    $status = $_POST['status'];
    $dob = $_POST['dob'];

    // include db connect class
    require_once __DIR__ . '/user_info_connect.php';

    // connecting to db
    $db = new USER_INFO_CONNECT();

    // mysql inserting a new row
    $result = mysql_query("INSERT INTO user_info(name, first_name, last_name, number, email, status, dob) VALUES('$name', '$first_name', '$last_name', '$number', '$email', '$status', '$dob')");

    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "User successfully created.";

        // echoing JSON response
        echo json_encode($response);
    } else {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";

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

    // echoing JSON response
    echo json_encode($response);
}
?>

下面是MySQL数据库中数据库结构的快照。 This is a snapshot of the database structure in the MySQL Database.

此代码的问题在于,当我调试它时,查询永远不会成功运行,它总是会得到以下输出“缺少必填字段”。这意味着缺少数字字段,但为了实验,我甚至对用户对象中的数字进行了硬编码。对于我的生活,我真的无法理解为什么params没有被代码拾取。请帮忙。

我尝试直接从浏览器执行此查询来测试我的php文件。     http://115.118.217.53:8068/osachat_connect/create_user.php?name=Rayzone&firstname=Ray&number=97179&lastname=zone&email=a@b&status=hoqdy&dob=3/7/89

即使在这里我得到了回复

create_user.php {"success":0,"message":"Required field(s) is missing"}

1 个答案:

答案 0 :(得分:1)

显然你需要更好的调试技巧,如果你得到Required field(s) is missing意味着不符合以下条件:

if (isset($_POST['number'])) {...}

所以你应该找出为什么android没有设置那个参数。

params.add(new BasicNameValuePair("number", number));

记录下来:

Log.d("mylog", "number = " + number);

用PHP调试

error_log('**********************DEBUG************************');
ob_start();
var_dump($_POST);
$postBack = ob_get_contents();
ob_end_clean();
error_log($postBack);
error_log('**********************DEBUG************************');

试试我的功能:

public static String apiCaller(List<NameValuePair> params, url){

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);

    String jsonString = null;

    try {
        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity respEntity = response.getEntity();

        if (respEntity != null) {
            InputStream inputStream =  respEntity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inputStream, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            inputStream.close();

            jsonString = sb.toString();
            Log.d(LOG_TAG, jsonString);

        }
    } catch (UnsupportedEncodingException e) {
        // writing error to Log
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // writing exception to log
        e.printStackTrace();
    } catch (IOException e) {
        // writing exception to log
        e.printStackTrace();
    }

    return jsonString;
}