java - 变量未发送到服务器

标签 java php android mysql

我正在尝试从我的应用程序将数据插入数据库。我可以获取数据,但是当我尝试将变量传递到服务器时,出现“缺少必填字段”错误。

我之前曾使用不同的应用程序完成过此操作,但那是在我的网站上安装 SSL 之前。 SSL 是否有可能阻止变量。

出于测试目的,我尝试使代码尽可能简单,但我就是无法弄清楚。我重新完成了几个教程只是为了确保我没有犯错误,但显然我在某个地方出错了。非常感谢任何帮助!

    class CreateNewProduct extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(NewProductActivity.this);
            pDialog.setMessage("Creating Product..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        protected String doInBackground(String... args) {

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", "name"));
            params.add(new BasicNameValuePair("price", "2"));
            params.add(new BasicNameValuePair("imgurl", "imgurl"));

            JSONObject json = jsonParser.makeHttpRequest("http://myserver.com",
                    "POST", params);

            Log.d("Create Response", json.toString());

            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                    startActivity(i);

                    finish();
                } else {
Log.d("TEST", "Failed to create product");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(String file_url) {
            pDialog.dismiss();
        }

    }

PHP 代码:

<?php

$response = array();

if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['imgurl'])) {

    $name = "joey";
    $price = "3";
    $imgurl = "blowey";

    require_once __DIR__ . '/db_connect.php';

    $db = new DB_CONNECT();

    $result = mysqli_query("INSERT INTO products(name, price, imgurl) VALUES('$name', '$price', '$imgurl')");

    if ($result) {
        $response["success"] = 1;
        $response["message"] = "Product successfully created.";
        echo json_encode($response);
    } else {
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";
        echo json_encode($response);
    }
} else {
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
    echo json_encode($response);
}
?>

JSON 解析器:

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();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

                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 + "\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;

    }
}

最佳答案

尝试替换:

 post.setEntity(new UrlEncodedFormEntity(dataToSend));

 post.setRequestBody(dataToSend);

关于java - 变量未发送到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30333454/

相关文章:

Java : Quartz scheduler - is there a way I can get next five runs of a scheduled job

java - Java中NavigableSet、SortedSet和TreeSet的区别

java - Java 中的 W3C dom api

php - 如果 MSSQL 表列为 NULL,如果语句不起作用,则使用 PHP 使用 JS 更改 CSS 样式

php - 从 php/linux 获取 pdf 的布局模式(横向或纵向)

android - 带有自定义 ArrayAdapter 的 ArrayList

java - 使用三元数组对Arrays.asList(T…)的不同行为

php - 如何从 php 或 postgresql 中的当前查询获取表名

java - 创建自定义适配器类以避免自定义 ListView

android - 在 flutter 应用程序中添加 image_picker 插件后,Gradle 构建失败