Jack1204
Jack1204

Reputation: 31

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. Is there any chance SSL could be stopping the variables.

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

$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:

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;

    }
}

Upvotes: 0

Views: 71

Answers (1)

Alex
Alex

Reputation: 17289

Try to replace:

 post.setEntity(new UrlEncodedFormEntity(dataToSend));

with

 post.setRequestBody(dataToSend);

Upvotes: 1

Related Questions