从php获取echo消息

时间:2015-03-11 18:23:07

标签: php android json

我正在做httppost方法,以便向php发送3个参数。 3个参数用于mysql查询以检索特定记录。 但是,我的json.getInt()指向null。有什么方法可以得到回音信息吗?

    protected String doInBackground(String... args) {

            // updating UI from Background Thread


                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("item_ID", itemID));
                    params.add(new BasicNameValuePair("booking_StartDate", checkStartDate));
                    params.add(new BasicNameValuePair("booking_EndDate", checkEndDate));

                    JSONObject json = jParser.makeHttpRequest(url_checkAvaibility, "POST", params);
                    // Check for success tag

                    try {
                        int success = json.getInt(TAG_SUCCESS);
                        if(records == null){
                            success =0;
                        }
                        else
                        {
                            success =1;
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }



            return null;
        }

<?php

/*
 * Following code will get single product details
 * A product is identified by product id (pid)
 */

// array for JSON response
$response = array();

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

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

// check for post data
$item_ID = $_POST['item_ID'];
$bookingStartDate = $_POST['booking_StartDate'];
$bd2 = strtotime($bookingStartDate);
$bd3 = date('Y-m-d',$bd2);
$bookingEndDate = $_POST['booking_EndDate'];
$be2 = strtotime($bookingEndDate);
$be3 = date('Y-m-d',$be2);


    // get a product from products table
    $result = mysql_query("SELECT booking_ID,booking_Title FROM booking_record where booking_Status='Approved' and item_ID='$item_ID' and (booking_StartDate between '$bd3' and '$be3' or booking_EndDate between '$bd3' and '$be3')") or die(mysql_error());

    if (!empty($result)) {
    if (mysql_num_rows($result) != 0) {

        $result = mysql_fetch_array($result);
        // check for empty result
            $record = array();
            $record ["booking_ID"] = $result["booking_ID"];
        $record ["booking_Title"] = $result["booking_Title"];
        $response["records"] = array();     

        array_push($response["records"], $record);
            $response["success"] = 1;


       echo json_encode($response);




        } else {
            // no product found
            $response["success"] = 0;
            $response["message"] = "No product found";

            // echo no users JSON
            echo json_encode($response);
        }}else{
        $response["success"] = 0;
            $response["message"] = "Error";
}


?>

我在这一行得到空指针异常。

int success = json.getInt(TAG_SUCCESS);

JSON makeHttpRequest方法

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();
               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"){
               // 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);
               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);
           }
           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);
       } catch (JSONException e) {
           Log.e("JSON Parser", "Error parsing data "+json + e.toString());
       }*/

       // return JSON String
     try {
        return new JSONObject(json);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

     return null;
   }

logcat的

> 03-12 02:36:57.928: E/AndroidRuntime(12689): FATAL EXCEPTION:
> AsyncTask #1 03-12 02:36:57.928: E/AndroidRuntime(12689):
> java.lang.RuntimeException: An error occured while executing
> doInBackground() 03-12 02:36:57.928: E/AndroidRuntime(12689):     at
> android.os.AsyncTask$3.done(AsyncTask.java:278) 03-12 02:36:57.928:
> E/AndroidRuntime(12689):  at
> java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
> 03-12 02:36:57.928: E/AndroidRuntime(12689):  at
> java.util.concurrent.FutureTask.setException(FutureTask.java:124)
> 03-12 02:36:57.928: E/AndroidRuntime(12689):  at
> java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
> 03-12 02:36:57.928: E/AndroidRuntime(12689):  at
> java.util.concurrent.FutureTask.run(FutureTask.java:137) 03-12
> 02:36:57.928: E/AndroidRuntime(12689):    at
> android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208) 03-12
> 02:36:57.928: E/AndroidRuntime(12689):    at
> java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
> 03-12 02:36:57.928: E/AndroidRuntime(12689):  at
> java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
> 03-12 02:36:57.928: E/AndroidRuntime(12689):  at
> java.lang.Thread.run(Thread.java:856) 03-12 02:36:57.928:
> E/AndroidRuntime(12689): Caused by: java.lang.NullPointerException
> 03-12 02:36:57.928: E/AndroidRuntime(12689):  at
> com.example.mysqltesting.ShowAvaibility$GetProductDetails.doInBackground(ShowAvaibility.java:89)
> 03-12 02:36:57.928: E/AndroidRuntime(12689):  at
> com.example.mysqltesting.ShowAvaibility$GetProductDetails.doInBackground(ShowAvaibility.java:1)
> 03-12 02:36:57.928: E/AndroidRuntime(12689):  at
> android.os.AsyncTask$2.call(AsyncTask.java:264) 03-12 02:36:57.928:
> E/AndroidRuntime(12689):  at
> java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
> 03-12 02:36:57.928: E/AndroidRuntime(12689):  ... 5 more

这是我得到的最新logcat

03-12 03:54:28.956: D/JSON-OUTPUT(22405): <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>403 Forbidden</title></head><body><h1>Forbidden</h1><p>You don't have permission to access /checkAva.phpon this server.</p><hr><address>Apache/2.4.9 (Win64) PHP/5.5.12 Server at 192.168.1.132 Port 80</address></body></html>
03-12 03:54:28.961: E/JSON Parser(22405): Error parsing data <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>403 Forbidden</title></head><body><h1>Forbidden</h1><p>You don't have permission to access /checkAva.phpon this server.</p><hr><address>Apache/2.4.9 (Win64) PHP/5.5.12 Server at 192.168.1.132 Port 80</address></body></html>org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

1 个答案:

答案 0 :(得分:0)

以下是审核错误后需要执行的操作,

您需要编辑etc / apache2 / httpd.conf并确保您拥有require all granted,这将允许您网络上的任何人访问您所服务的文件夹注意:我在Mac上。

DocumentRoot "/Users/USER_NAME_HERE/FOLDER_YOU_SERVE_FROM/"
<Directory "/Users/USER_NAME_HERE/FOLDER_YOU_SERVE_FROM/">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options FollowSymLinks Multiviews
    MultiviewsMatch Any

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   AllowOverride FileInfo AuthConfig Limit
    #
    AllowOverride All

    #
    # Controls who can get stuff from this server.
    #
    Require all granted
</Directory>