如何通过Android将参数发布到PHP后检索json数组

Posted

技术标签:

【中文标题】如何通过Android将参数发布到PHP后检索json数组【英文标题】:How to retrieve the json array after post parameter to PHP through Android 【发布时间】:2017-02-14 15:40:48 【问题描述】:

这是我的 JAVA 类,我有 Sendphp() AsyncTask 将我选择的日期发布到 PHP 和另一个 RequestTask() AsyncTask 来检索我的 JSON 数组

    public class CustomerPage extends Fragment 
    private FragmentActivity activity;
    private RecyclerView rv;
    private LinearLayoutManager layoutManager;
    private AlertDialog alertDialog;
    private List<Customer> customers;
    private RequestTask task;
    private CustomerAdapter adapter;
    private String url ="http://eac.asia/eacsales/Newstar/get_customer.php";
    private String TAG_STATUS = "status";
    private String TAG_CUSTOMER = "customers";
    private Calendar calendar;
    private int year,month,day;
    private TextView tvDate;
    private ImageView imgSearch;
    private String output;
    String strDay , strMonth,strYear;

@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    activity = (FragmentActivity) getActivity();


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    View v = inflater.inflate(R.layout.customer_page,container,false);
    rv = (RecyclerView) v.findViewById(R.id.rvCustomer);
    tvDate = (TextView)v.findViewById(R.id.dateView);
    imgSearch = (ImageView)v.findViewById(R.id.img_search);
    layoutManager = new LinearLayoutManager(getActivity());
    calendar = Calendar.getInstance();
    year = calendar.get(Calendar.YEAR);
    month = calendar.get(Calendar.MONTH);
    day = calendar.get(Calendar.DAY_OF_MONTH);

    rv.setLayoutManager(layoutManager);
    rv.setItemAnimator(new DefaultItemAnimator());

    tvDate.setOnClickListener(new View.OnClickListener() 
        @SuppressWarnings("deprecation")
        @Override
        public void onClick(View v) 
            DialogFragment dialogFragment = new DateFragment();
            dialogFragment.show(getActivity().getSupportFragmentManager(), "DatePicker");
        
    );

    return v;


@Override
public void onResume() 
    super.onResume();


private void sendRequest() 
    if (enableNetwork()) 
        task = new RequestTask();
        task.execute(url);
     else 
        showAlertDialog("No Internet Connection");
    

public void showAlertDialog(String message) 
    alertDialog = new AlertDialog.Builder(getActivity()).create();
    alertDialog.setMessage(message);
    alertDialog.setCancelable(false);

    alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
            new DialogInterface.OnClickListener() 
                public void onClick(DialogInterface dialog, int which) 
                    dialog.dismiss();
                
            );
    alertDialog.show();

@Override
public void onSaveInstanceState(Bundle outState) 
    super.onSaveInstanceState(outState);


private class RequestTask extends AsyncTask<String, Void, List<Customer>> 

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

    @Override
    protected List<Customer> doInBackground(String... urls) 
        try 
            JSONObject jsonObject = getJsonObject(urls[0]);
            Log.d("All data: ", jsonObject.toString());

            if (jsonObject != null) 
                boolean status = jsonObject.getBoolean(TAG_STATUS);
                Log.d("Status: ", String.valueOf(status));

                if (status) 
                    customers = CustomerJsonReader.getHome(jsonObject.getJSONArray(TAG_CUSTOMER));
                 else 

                

            else 
                showAlertDialog("Connection Problem");
            
            URL url = new URL("http://eac.asia/eacsales/Newstar/get_customer.php");
            URLConnection con = url.openConnection();
            con.setDoOutput(true);
            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;

            // Read Server Response
            while((line = reader.readLine()) != null)
            
                // Append server response in string
                sb.append(line + "\n");
            
            Log.d("Return Post",sb.toString());
         catch (Exception e) 
            e.printStackTrace();
        
        return customers;
    
    /**
     * It returns jsonObject for the specified url.
     *
     * @param url
     * @return JSONObject
     */
    public JSONObject getJsonObject(String url) 
        JSONObject jsonObject = null;
        try 
            jsonObject = GetJSONObject.getJSONObject(url);
         catch (Exception e) 
        
        return jsonObject;
    

    @Override
    protected void onPostExecute(List<Customer> result) 
        super.onPostExecute(result);

        customers = result;
            if (customers != null && customers.size() != 0) 
                getActivity().runOnUiThread(new Runnable() 
                    @Override
                    public void run() 
                        adapter = new CustomerAdapter(getActivity(), customers);
                        rv.setAdapter(adapter);
                    
                );
            else
                Toast.makeText(getActivity(), "No Product found", Toast.LENGTH_SHORT).show();
            
    

public boolean enableNetwork() 

    ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null) 
        NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()
                && netInfo.isConnectedOrConnecting()
                && netInfo.isAvailable()) 
            return true;
        
    
    return false;

class DateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener 

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) 
        final Calendar calendar = Calendar.getInstance();
        int yy = calendar.get(Calendar.YEAR);
        int mm = calendar.get(Calendar.MONTH);
        int dd = calendar.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog dp = new DatePickerDialog(getActivity(), AlertDialog.THEME_HOLO_LIGHT,this,yy,mm,dd);
            return dp;

    

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) 
        populateSetDate(year,monthOfYear+1,dayOfMonth);
    

    public void populateSetDate(int year, int month, int day) 
        tvDate.setText(month + "/" + day + "/" + year);
        strDay = String.valueOf(day);
        strMonth = String.valueOf(month);
        strYear = String.valueOf(year);
        new SendPHPRequest(getActivity()).execute(strDay,strMonth,strYear);
    


class SendPHPRequest extends AsyncTask<String, Void, String> 
    private Context context;

    public SendPHPRequest(Context context)
        this.context = context;
    
    @SuppressWarnings("deprecation")
    @Override
    protected String doInBackground(String... params) 

        String day = params[0];
        String month = params[1];
        String year = params[2];
        StringBuilder sb = null;

        System.out.println("*** doInBackground ** day " + day + " month :" + month +"year :"+year);
        try 
            String data = URLEncoder.encode("day", "UTF-8")
                    + "=" + URLEncoder.encode(day, "UTF-8");
            data += "&" + URLEncoder.encode("month", "UTF-8") + "="
                    + URLEncoder.encode(month, "UTF-8");
            data += "&" + URLEncoder.encode("year", "UTF-8") + "="
                    + URLEncoder.encode(year, "UTF-8");

            URL url = new URL("http://eac.asia/eacsales/Newstar/get_customer.php");
            URLConnection con = url.openConnection();
            con.setDoOutput(true);

            OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
            wr.write(String.valueOf(data));
            wr.flush();

            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            sb = new StringBuilder();
            String line = null;

            // Read Server Response
            while((line = reader.readLine()) != null)
            
            // Append server response in string
                sb.append(line + "\n");
            
            //noinspection ResourceType


         catch (UnsupportedEncodingException uee) 
            System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
            uee.printStackTrace();
         catch (ClientProtocolException e) 
            e.printStackTrace();
         catch (IOException e) 
            e.printStackTrace();
        
        return null;
    

    @Override
    protected void onPostExecute(String result) 
        super.onPostExecute(result);
        sendRequest();
    

这是我的 PHP 代码,用于从 android 获取日期并根据日期从数据库中选择结果,然后将结果显示为 JSON 对象

    <?php
$con = mysql_connect("localhost","eac_sale_database","a123456Z","eac_sale_database");
$db = mysql_select_db("eac_sale_database");

$response = array();

$day = urldecode($_POST['day']);
$month = urldecode($_POST['month']);
$year = urldecode($_POST['year']);

$result = mysql_query("SELECT * FROM customer WHERE day_visit = '$day' AND month_visit = '$month' AND year_visit = '$year'")or die(mysql_error());

if(mysql_num_rows($result)> 0)
    $response["customers"] = array();
        while($row = mysql_fetch_array($result))
            $product = array();
            $product["custNo"] = $row["no"];
            $product["custName"] = $row["name"];
            $product["netSales"] = $row["net_sales"];
            $product["dayVisit"] = $row["day_visit"];
            $product["monthVisit"] = $row["month_visit"];
            $product["yearVisit"] = $row["year_visit"];
            $product["dateVisit"] = $row["date_visit"];
            array_push($response["customers"], $product);
    
    $response["status"] = "true";
    header('Content-Type: application/json');
    header('Vary: User-Agent');

    echo json_encode($response);


  else
      $response["status"] = "false";
     echo json_encode($response);
  

?>

但是,我在 android 日志中的输出显示“status”=“false”。 我非常确定我的日期参数已经发布到 PHP 中,但它无法进行查询和输出。有解决办法吗?请帮忙。

This is the date in my database

DATA Sent get the JSONobject but it should be displayed in RequestTask()

【问题讨论】:

尝试print_r($_POST) 并检查输出。 您的意思是将 json_encode() 替换为 print_r($_POST)? @RaxWeber 试试这个:print_r(json_encode($response)) 我使用 Log.d 检查 print_r() 的结果,但它只是返回: Post: "status":"false" @RaxWeber 哦,等等,将$response 替换为$_POST。我们已经知道$response 包含什么。 【参考方案1】:

问题出在你的 php 方面:

    $con = mysql_connect("localhost","eac_sale_database","a123456Z");

这里只需要3个参数,因为你已经写好了

$db = mysql_select_db("eac_sale_database");

    这样做:

    $day = urldecode($_GET['day']); $month = urldecode($_GET['month']); $year = urldecode($_GET['year']);

使用postman 验证您的代码并确保您的用户名和密码正确,因为您的用户名和数据库名称不应该相同。

我尝试了你的代码在我这边创建了一个数据库和 php 文件,我得到了一个这样的 json 对象:

"customers":["custNo":"1","custName":"Rushi","netSales":"30000","dayVisit":"5","monthVisit":"7","yearVisit":"2016","dateVisit":"2016-10-05 10:24:33"],"status":"true"

为什么你有相同的文件用于插入数据库和从数据库获取? 您必须为两者创建不同的文件。另外,您为什么不返回 doInBackground?我认为如果您请求与您在 sendPHP 中请求的方式相同的请求,您的 requestTask 将正常工作,因为这是您的 php 查询正在执行的操作。您在 RequestTask 中的请求不包含任何要搜索的参数。你需要了解更多关于 php 的知识。

我的 PHP。 如果请求的 url 如下所示,它将返回与特定日期对应的行: :http://localhost/stacktest/get_customer.php?day=5&amp;month=7&amp;year=2016 并返回所有详细信息,如果请求的 URL 类似于:http://localhost/stacktest/get_customer.php 希望你明白我的意思。您需要更改 php 端的 sql 查询和 android 端的请求。

<?php
$con = mysql_connect("localhost","root","");
$db = mysql_select_db("stacktest");

$response = array();
print_r($_GET);
if(isset($_GET['day']))

$day = urldecode($_GET['day']);
$month = urldecode($_GET['month']);
$year = urldecode($_GET['year']);

$result = mysql_query("SELECT * FROM customer WHERE day_visit = '$day' AND month_visit = '$month' AND year_visit = '$year'")or die(mysql_error());

if(mysql_num_rows($result)> 0)
    $response["customers"] = array();
        while($row = mysql_fetch_array($result))
            $product = array();
            $product["custNo"] = $row["no"];
            $product["custName"] = $row["name"];
            $product["netSales"] = $row["net_sales"];
            $product["dayVisit"] = $row["day_visit"];
            $product["monthVisit"] = $row["month_visit"];
            $product["yearVisit"] = $row["year_visit"];
            $product["dateVisit"] = $row["date_visit"];
            array_push($response["customers"], $product);
    
    $response["status"] = "true";
    header('Content-Type: application/json');
    header('Vary: User-Agent');

    echo json_encode($response);


  else
      $response["status"] = "false";
     echo json_encode($response);
  

else
    $result = mysql_query("SELECT * FROM customer ")or die(mysql_error());

if(mysql_num_rows($result)> 0)
    $response["customers"] = array();
        while($row = mysql_fetch_array($result))
            $product = array();
            $product["custNo"] = $row["no"];
            $product["custName"] = $row["name"];
            $product["netSales"] = $row["net_sales"];
            $product["dayVisit"] = $row["day_visit"];
            $product["monthVisit"] = $row["month_visit"];
            $product["yearVisit"] = $row["year_visit"];
            $product["dateVisit"] = $row["date_visit"];
            array_push($response["customers"], $product);
    
    $response["status"] = "true";
    header('Content-Type: application/json');
    header('Vary: User-Agent');

    echo json_encode($response);


?>

如果您只想显示与给定日期对应的数据,请执行以下操作:

class SendPHPRequest extends AsyncTask<String, Void, String> 
               ...
               ...
               ...
                protected String doInBackground(String... params) 
                 ...
                 ...
                 return sb.toString();
                 
                    protected void onPostExecute(String result) 
                    RequestTask(result);
                

RequestTask 中只做 json 解析。否则就不需要RequestTask。

保持你的 php 为:

<?php
    $con = mysql_connect("localhost","root","");
    $db = mysql_select_db("stacktest");

    $response = array();

    $day = urldecode($_GET['day']);
    $month = urldecode($_GET['month']);
    $year = urldecode($_GET['year']);

    $result = mysql_query("SELECT * FROM customer WHERE day_visit = '$day' AND month_visit = '$month' AND year_visit = '$year'")or die(mysql_error());

    if(mysql_num_rows($result)> 0)
        $response["customers"] = array();
            while($row = mysql_fetch_array($result))
                $product = array();
                $product["custNo"] = $row["no"];
                $product["custName"] = $row["name"];
                $product["netSales"] = $row["net_sales"];
                $product["dayVisit"] = $row["day_visit"];
                $product["monthVisit"] = $row["month_visit"];
                $product["yearVisit"] = $row["year_visit"];
                $product["dateVisit"] = $row["date_visit"];
                array_push($response["customers"], $product);
        
        $response["status"] = "true";
        header('Content-Type: application/json');
        header('Vary: User-Agent');

        echo json_encode($response);

    
      else
          $response["status"] = "false";
         echo json_encode($response);
      

    ?>

【讨论】:

感谢您的解释!我在这里有一些问题:Erm ...如果我使用GET方法链接PHP,我可以这样使用:'JSONObject jsonObject = getJsonObject(link)'链接是“http://....get_customer. php?month=..” 天哪!!!!你简直是天才!!!有用!!!但我需要删除 print_r();否则它无法读取我的 json 对象。非常感谢! 而且我认为我无法在 android 上显示我的对象的主要问题是因为我将参数发送和结果获取分开。 ...但是为什么当我使用上面的POST方法时它不起作用? @VincentTang 感谢您的支持和赞赏。现在对于您的其他问题:1.不,您不能像那样直接发布链接。您必须通过 URLConnection 打开连接才能通过网络发送数据。 2. 是的,你可以使用 GET 或 POST 任何你喜欢的东西。它也适用于 POST。我的错。 :)【参考方案2】:

1).尝试将您的URLConnection 更改为HttpURLConnection 并设置POST 请求方法。

发件人:

URLConnection con = url.openConnection();
con.setDoOutput(true);

收件人:

HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");

2). 转储并检查您在 php 中的 $_POST,var_dump($_POST);die(); 结果应如下所示:

array(3) 
  ["day"]=>
  string(1) "6"
  ["month"]=>
  string(7) "10"
  ["year"]=>
  string(4) "2016"

3).如果您想以 JSON 格式发送请求,您可能需要尝试

con.setRequestProperty("Content-Type","application/json");

4).如果您的请求正文是 JSON,请尝试:

$json = file_get_contents('php://input');
$date = json_decode($json);

你会得到$date["day"], $date["month"] and $date["year"]

5). 尝试在 php 中添加响应标头,如下所示:

header('Content-Type: application/json');
header('Vary: User-Agent');

echo json_encode($response);

注意:使用Postman 之类的工具来验证您的请求和 API 是否有效 与否。

【讨论】:

查询语句已经可以运行了,我也得到了我想要的结果!但是这里有一个问题,结果在 SendPHP() 而不是 RequestTask() 中返回。我的 RequestTask() 不断得到显示在 PHP 中的输出,即 status:false,这就是为什么它不能帮助我将结果转换为我的回收视图 你能告诉我你的var_dump($_POST);来自php吗? 我刚刚更新了上面的 PHP 代码,请看一下@kolunar 我发现结果返回的是字符串而不是JSONObject

以上是关于如何通过Android将参数发布到PHP后检索json数组的主要内容,如果未能解决你的问题,请参考以下文章

如何通过 android 中的改造从 php 中检索“字符串响应”?

未在 php 文件中检索到 ajax 数据参数

jquery - 如何使用通过 AJAX 从 MySQL 和 PHP 检索的数据将图像添加到 Select2 下拉列表?

如何将 android 应用程序连接到 MYSQL 服务器并从中检索数据?

通过 PHP 检索 GET 变量,在同一脚本上发送到 SWF?

通过 JSON 将数据从 android 发送到服务器