【问题标题】:For each loop is not executing when uploaded at 000webhost server在 000webhost 服务器上上传时,每个循环都没有执行
【发布时间】:2014-07-07 08:50:01
【问题描述】:

我有一个将数据发布到在线服务器中的 php 文件的应用程序。帖子完成后,我得到一堆 html 代码。其中说我有一个 php 错误,这是第 33 行上为 each() 提供的无效参数。但是,如果我在 localhost 中运行它,则不会发生此问题。我不明白为什么会出现这个问题。所以请有人帮我解决它。

以下是我的jsonparser类

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getandpostJSONFromUrl(String url, String method,JSONArray name) {

        // Making HTTP request
        try {
            // defaultHttpClient
            if (method == "POST") {


                HttpParams params = new BasicHttpParams();
                //params.setParameter("data", auth);
                HttpClient httpclient = new DefaultHttpClient(params);

                HttpPost httpPost = new HttpPost(url);


                List<NameValuePair> postParams = new ArrayList<NameValuePair>();
                postParams.add(new BasicNameValuePair("json", name.toString()));

                for (NameValuePair nvp : postParams) {
                    String name2 = nvp.getName();
                    String value = nvp.getValue();
                    Log.d("NameValue pair content", ""+name2+""+value);
                }


                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams,HTTP.UTF_8);


                httpPost.setEntity(entity);
                HttpResponse response = httpclient.execute(httpPost);
                String responseBody = EntityUtils.toString(response.getEntity()); 
                Log.d("",responseBody);
            }
            if (method == "GET") {

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

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

            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (method == "POST") {
            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is));
            } catch (Exception e) {
                Log.e("Buffer error", "Buffer error" + e);
            }

        } else if (method == "GET") {

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

        // return JSON String
        return jObj;

    }

}

以下是服务器上的php文件

<?php
        header('Content-type: application/json');
        /*define('DB_NAME', 'a1422982_sshop');
                        define('DB_USER', 'root');
                        define('DB_PASSWORD', '');
                        define('DB_HOST', 'localhost');*/

        define('DB_NAME', 'onlineshop');
        define('DB_USER', 'shop');
        define('DB_PASSWORD', 'pass');
        define('DB_HOST', 'mysql28.000webhost.com'); 


                        $link = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);

                        if(!$link){
                        die('could not connect: '.msql_error());
                        }

                        $db_selected=mysql_select_db(DB_NAME, $link);

                        if(!$db_selected){
                        die('Can not  use '.DB_NAME.':'.mysql_error());
                        }

                        //var_dump(json_decode ($_POST['json'])));

                        if($_POST['json']){
                            $parsed = json_decode($_POST['json'],TRUE);

                            $i=0;

                            foreach ($parsed as $obj) {
                                 $ProductName = $obj['Name'];   
                                 $ProductQuantity= $obj['Quantity'];
                                 $sql="Update productlist Set Quantity='$ProductQuantity' where Name='$ProductName';";

                                 $retval = mysql_query( $sql, $link );
                                  if(! $retval )
                                    {
                                      die('Could not get data: ' . mysql_error());
                                    }
                                 $i++;

                                 echo   $ProductName." ".$ProductQuantity;
                             }
                        }else{
                            echo "empty";
                        }


?>

【问题讨论】:

  • 你应该在你的PHP文件的开头添加error_reporting(E_ALL);,你可能会看到一些错误
  • 不要离开搜索第 33 行,而是告诉它是哪一行。
  • if($_POST['json']){ 最好改为if (isset($_POST['json'])){
  • 第 33 行-> foreach ($parsed as $obj) {@greenapps
  • 那么 $parsed 无效。找出为什么。打印出来或让脚本返回 json 文本,看看它是否与您发布的不同。并使用 isset()!告诉您是否应用了所有建议的更改。

标签: java php android json


【解决方案1】:

您的 HttpPost 请求中缺少选项,将实体元数据和生成的实体设置为字符串。

在您的 java 代码中,您可以这样做:

   Map<String, String> postData = new HashMap<String, String>();
   postData.put("KEY", "yourvalue");
   JSONObject holder = new JSONObject(postData);

   StringEntity jsonStringEntity = new StringEntity(holder.toString());

   httpost.setEntity(jsonStringEntity);
   httpost.setHeader("Accept", "application/json");
   httpost.setHeader("Content-type", "application/json");

这样,您的 PHP 代码实际上可以解析您的帖子数据,因为 json_decode() 期望 json 作为参数。

【讨论】:

    猜你喜欢
    • 2014-02-16
    • 2016-03-17
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    • 2020-06-21
    • 1970-01-01
    • 2014-07-02
    相关资源
    最近更新 更多