【问题标题】:HttpPost request returning bad responseHttpPost 请求返回错误响应
【发布时间】:2013-03-14 23:54:28
【问题描述】:

我正在尝试将HttpRequest 发送到位于 Web 服务器上的 php 脚本。我想检索特定类别的所有菜肴。菜肴以JSON 格式返回,我的JSONParser 类在其中解析数据。

下面是我的doInBackground 方法,我在其中请求文件:

    @Override
    protected Boolean doInBackground(String... params) {
        // location of file to retrieve
        String url = "http://www.jdiadt.com/getAllDishes.php";
        JSONObject json = jParser.makeHttpRequest(url, "POST", cat);
        // For testing purposes - Ensure all data was received.
        Log.d("SINGLE DISH DETAILS: ", json.toString());

        try {
            int success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                dishes = json.getJSONArray(TAG_DISHES);
                for (int i = 0; i < dishes.length(); i++) {
                    JSONObject d = dishes.getJSONObject(i);
                    MenuItem m = new MenuItem();
                    m.setName(d.getString(TAG_NAME));
                    m.setPrice(Double.parseDouble(d.getString(TAG_PRICE)));
                    Log.d("MENUITEM " + i + ":", " NAME:" + m.getName()
                            + " PRICE:" + m.getPrice());
                    starters.add(m);
                }
            } else {
                return false;
            }

            return true;

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

这是JSONParser 类的makeHttpRequest() 方法:

public JSONObject makeHttpRequest(String url, String method, String cat) {

    // 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);

            List <NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("cat", cat));
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

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

        }

这是我试图检索的脚本:

$response = array();

   //Variables for connecting to your database.
            //These variable values come from your hosting account.
            $hostname = "xxx.xxx.xxx.xxx";
            $username = "xxxxxx";
            $dbname = "xxxxxxx";



            //These variable values need to be changed by you before deploying
            $password = "xxxxxxxxxxx";
            $usertable = "dishes";
            $yourfield = "dish_name";

            //Connecting to your database
            mysql_connect($hostname, $username, $password) OR DIE ("Unable to 
            connect to database! Please try again later.");
            mysql_select_db($dbname);

            $cat = $_POST['cat'];


// get all dishes from dishes table
$result = mysql_query("SELECT * FROM $usertable where dish_cat = '$cat' ") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // dishes node
    $response["dishes"] = array();

    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $dishes = array();
        $dishes["dish_id"] = $row["dish_id"];
        $dishes["dish_name"] = $row["dish_name"];
        $dishes["dish_desc"] = $row["dish_desc"];
        $dishes["dish_price"] = $row["dish_price"];

        // push single dish into final response array
        array_push($response["dishes"], $dishes);
    }
    // success
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);
} else {
    // no dishes found
    $response["success"] = 0;
    $response["message"] = "No dishes found";

    // echo no users JSON
    echo json_encode($response);
}

注意这一行:

$cat = $_POST['cat']

这应该是检索菜品类别,并且 sql 语句应该成功执行....目前我收到一条消息,说“没有找到菜”。

任何帮助将不胜感激。我不知道我做错了什么。

【问题讨论】:

    标签: android http android-asynctask http-post httprequest


    【解决方案1】:

    我认为问题在于你的情况:

    if (method == "POST") {
      // execute request
    }
    

    在这里,您将 Strings 与 == 进行比较,这将始终返回 false(并且永远不会执行正文),因为它比较的是引用而不是值。你必须使用equals() 方法。

    if (method.equals("POST") {
       // do your work
    }
    

    【讨论】:

    • 我明白了,感谢您发现!应用程序仍然挂起,这让我想知道是我的脚本有问题吗?
    • @Javacadabra 也许是的,尝试写入日志响应,它应该返回什么?细绳?还是?
    【解决方案2】:

    请尝试打印 $cat 以确保您首先正确接收它。

    【讨论】:

    • 问题是我没有收到正确的值。谢谢
    猜你喜欢
    • 2019-10-18
    • 2023-03-25
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 2012-05-05
    • 2019-12-18
    相关资源
    最近更新 更多