简体   繁体   English

变量未发送到服务器

[英]Variables Not Being Sent To Server

I'm trying to insert data into the database from my app. 我正在尝试从我的应用程序将数据插入数据库。 I can fetch data, but when I try to pass variables to my server, I get the "Required field(s) is missing" error. 我可以获取数据,但是当我尝试将变量传递到服务器时,出现“缺少必填字段”错误。

I've done this before with a different app, but that was before I had SSL installed on my website. 我之前是使用其他应用程序完成此操作的,但是那是在我的网站上安装SSL之前的。 Is there any chance SSL could be stopping the variables. SSL是否有可能停止变量。

I tried keeping the code as simple as possible for testing purposes but I just can't figure it out. 为了测试目的,我尝试将代码保持尽可能简单,但是我无法弄清楚。 I have re-done several tutorials just to make sure I'm not making errors, but clearly I'm going wrong somewhere. 我已经重新做了一些教程,只是为了确保我没有犯错误,但是很显然我在某个地方出错了。 Any help much appreciated! 任何帮助,不胜感激!

    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 Code: 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 Parser: 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;

    }
}

Try to replace: 尝试更换:

 post.setEntity(new UrlEncodedFormEntity(dataToSend));

with

 post.setRequestBody(dataToSend);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 服务器未正确读取发送的UDP数据包 - UDP Packet sent not being read by server correctly 没有通过URLConnection发送到服务器 - Nothing being sent to server via URLConnection 什么是HttpPost发送到服务器和服务器响应之间的延迟 - what is delay between HttpPost being sent to server and server responding Android的问题是能够将发布请求发送到我的服务器 - Having issues with Android being able to sent post requests to my server 传入React时服务器发送的事件被复制 - Server sent events being multiplicated when incoming to React 如何读取通过Ajax发送到Java服务器的Blob - How to read a blob being sent through ajax to a Java server Spring发送的服务器已发送事件,线程已从请求中释放 - Server Sent Event with Spring with having a thread being freed from request 检查套接字发送的对象类型时,服务器未接收到对象 - Object not being received by server when checking for type of object sent by socket Netty 客户端中配置的密码列表未发送到服务器 - Cipher list configured in Netty client not being sent down to Server Netty 4.1:防止在服务器异常上发送 TCP ACK - Netty 4.1: preventing TCP ACK from being sent on server exception
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM