2015-05-19 72 views
0

我試圖從我的應用程序插入數據到數據庫中。我可以獲取數據,但是當我嘗試將變量傳遞到我的服務器時,出現「必填字段丟失」錯誤。變量不被髮送到服務器

我以前用不同的應用程序完成此操作,但是之前我在我的網站上安裝了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; 

    } 
} 
+0

你確定你的insert語句正確嗎? 'INSERT INTO products SET name =?,price =?,description =? ' - 通常'插入產品**值**(...)' - 但它可能是數據庫特定的mySql? –

+0

'我得到「必填字段丟失」錯誤。不可能,因爲你的代碼不讀取echo()的。 – greenapps

+0

@greenapps對不起!我正在嘗試一些不同的事情,並且意外地發佈了錯誤的代碼。我已經更新了代碼。此代碼給我「必填字段..」錯誤。 – Jack1204

回答

1

嘗試更換:

post.setEntity(new UrlEncodedFormEntity(dataToSend)); 

post.setRequestBody(dataToSend); 
+0

對不起,我意外地從一個不同的教程發佈了錯誤的代碼塊我是嘗試,現在已更新 – Jack1204

+0

*我得到「必填字段丟失」錯誤*您在哪裏看到此消息? – Alex

+0

在我的logcat中,JSON響應 - Log.d(「Create Response」,json。 toString()); – Jack1204