doucitan2544 2015-06-17 18:20
浏览 60

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

I'm trying to develop a simple Android application where I store a User's information onto a server. So I've developed the front end of my app, and I've created a MySql database on my server. I've written the PHP scripts required to update the database, and I've written a parser in my Android code to Parse and send data to the server.

The problem is, I'm unable to send parameters from my Android code to my PHP code. I've read numerous questions and answers on SO and many other forums, but nothing seems to work for me. Please help.

I've created an ASync Task that performs the task of sending the data to the server. Here's the code for the 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) {
    }
}

The 'url_create_product' in the above code is the URL to my server's PHP Create User file, which I'll also include later.

Next is my JSONParser file.

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

    }
}

Lastly, my create_user.php file is below.

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

Below is a snapshot of the database structure in the MySQL Database. This is a snapshot of the database structure in the MySQL Database.

The problem with this code is that when I debug it, the query never successfully runs, it always gets the following output "Required field(s) is missing". This means that the number field is missing, but for the sake of the experiment, I've even hard-coded the number in the user object. I really can't understand for the life of me why the params are not getting picked up by the code. Please help.

I tried executing this query directly from my browser to test my php file. 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

Even here I got the response

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

1条回答 默认 最新

  • duanshang9426 2015-06-17 18:25
    关注

    Obviously you need better debugging skills, if you get Required field(s) is missing means that the condition following is not met:

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

    So you should find out why android is not setting that parameter.

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

    log it:

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

    Debug in PHP

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

    Try my function:

    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 + "
    ");
                }
                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;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果