2015-06-17 46 views
0

我正在嘗試開發一個簡單的Android應用程序,用於將用戶信息存儲到服務器上。所以我開發了我的應用程序的前端,並且在我的服務器上創建了一個MySql數據庫。我已經編寫了更新數據庫所需的PHP腳本,並且我在Android代碼中編寫了一個解析器來解析併發送數據到服務器。無法從Android代碼向PHP發送參數

問題是,我無法從我的Android代碼發送參數到我的PHP代碼。我已經閱讀了許多關於SO和許多其他論壇的問題和解答,但似乎沒有任何效果。請幫忙。

我創建了一個ASync任務,執行將數據發送到服務器的任務。以下是Async Task的代碼。

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

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
    } 

    // Creating user 
    protected String doInBackground(String... args) { 
     String name = user.getName(); 
     String firstname = user.getFirstName(); 
     String lastname = user.getLastName(); 
     String number = user.getNumber(); 
     String email = user.getEmail(); 
     String status = user.getStatus(); 
     String dob = user.getDob(); 

     // Building Parameters 
     List<NameValuePair> params = new ArrayList<>(); 
     params.add(new BasicNameValuePair("name", name)); 
     params.add(new BasicNameValuePair("firstname", firstname)); 
     params.add(new BasicNameValuePair("number", number)); 
     params.add(new BasicNameValuePair("lastname", lastname)); 
     params.add(new BasicNameValuePair("email", email)); 
     params.add(new BasicNameValuePair("status", status)); 
     params.add(new BasicNameValuePair("dob", dob)); 

     JSONObject json = jsonParser.makeHttpRequest(url_create_product, 
       "POST", params); 

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

      if (success == 1) { 
      } else { 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 
    protected void onPostExecute(String file_url) { 
    } 
} 

在上面的代碼中的「url_create_product」是URL到我的服務器的PHP創建用戶文件,這也是我以後會包括。

接下來是我的JSONParser文件。

package com.osahub.rachit.osachatting.server; 

import android.util.Log; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.utils.URLEncodedUtils; 
import org.apache.http.entity.StringEntity; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.params.HttpConnectionParams; 
import org.apache.http.params.HttpParams; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.util.List; 

/** 
* Created by Rachit on 13-06-2015. 
*/ 
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(); 
       /*HttpParams httpParams = httpClient.getParams(); 
       HttpConnectionParams.setConnectionTimeout(httpParams, 10000); 
       HttpConnectionParams.setSoTimeout(httpParams, 10000);*/ 
       HttpPost httpPost = new HttpPost(url); 
       UrlEncodedFormEntity urlEncoded = new UrlEncodedFormEntity(params, "UTF-8"); 
       httpPost.setEntity(urlEncoded); 

       HttpResponse httpResponse = httpClient.execute(httpPost); 
       HttpEntity entity = httpResponse.getEntity(); 
       is = entity.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); 
       is = httpResponse.getEntity().getContent(); 
      } 

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

     // return JSON String 
     return jObj; 

    } 
} 

最後,我的create_user.php文件在下面。

create_user.php 
<?php 


$response = array(); 

// check for required fields 
if (isset($_POST['number'])) { 

    $name = $_POST['name']; 
    $first_name = $_POST['first_name']; 
    $number = $_POST['number']; 
    $last_name = $_POST['last_name']; 
    $email = $_POST['email']; 
    $status = $_POST['status']; 
    $dob = $_POST['dob']; 

    // include db connect class 
    require_once __DIR__ . '/user_info_connect.php'; 

    // connecting to db 
    $db = new USER_INFO_CONNECT(); 

    // mysql inserting a new row 
    $result = mysql_query("INSERT INTO user_info(name, first_name, last_name, number, email, status, dob) VALUES('$name', '$first_name', '$last_name', '$number', '$email', '$status', '$dob')"); 

    // check if row inserted or not 
    if ($result) { 
     // successfully inserted into database 
     $response["success"] = 1; 
     $response["message"] = "User successfully created."; 

     // echoing JSON response 
     echo json_encode($response); 
    } else { 
     // failed to insert row 
     $response["success"] = 0; 
     $response["message"] = "Oops! An error occurred."; 

     // echoing JSON response 
     echo json_encode($response); 
    } 
} else { 
    // required field is missing 
    $response["success"] = 0; 
    $response["message"] = "Required field(s) is missing"; 

    // echoing JSON response 
    echo json_encode($response); 
} 
?> 

下面是MySQL數據庫中數據庫結構的快照。 This is a snapshot of the database structure in the MySQL Database.

此代碼的問題是,當我調試它時,查詢從未成功運行,它總是得到以下輸出「缺少必需的字段(s)」。這意味着數字字段丟失了,但爲了實驗的緣故,我甚至對用戶對象中的數字進行了硬編碼。我真的無法理解爲什麼這些參數沒有被代碼拾起。請幫忙。

我試着直接從瀏覽器執行這個查詢來測試我的php文件。 http://115.118.217.53:8068/osachat_connect/create_user.php?name=Rayzone&firstname=Ray&number=97179&lastname=zone&[email protected]&status=hoqdy&dob=3/7/89

即使在這裏我得到的迴應

create_user.php {"success":0,"message":"Required field(s) is missing"} 
+1

[您的腳本存在SQL注入風險。](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) –

+1

如果可以,您應該[停止使用'mysql_ *'函數](http:// stackoverflow。COM /問題/ 12859942 /爲什麼 - 不應該,我使用MySQL的函數功能於PHP)。他們不再被維護,並[正式棄用](https://wiki.php.net/rfc/mysql_deprecation)。瞭解[準備](http://en.wikipedia.org/wiki/Prepared_statement)[聲明](http://php.net/manual/en/pdo.prepared-statements.php),並考慮使用PDO ,[這真的不難](http://jayblanchard.net/demystifying_php_pdo.html)。 –

+0

我瞭解風險。這僅僅是爲了教育目的。我試圖找出爲什麼我的代碼沒有按照應有的方式工作(考慮到所有風險) – Rachit

回答

1

顯然,你需要更好的調試技能,如果你得到Required field(s) is missing意味着繼條件不滿足:

if (isset($_POST['number'])) {...} 

所以,你應該找到爲什麼android不設置該參數。

params.add(new BasicNameValuePair("number", number)); 

記錄它:

Log.d("mylog", "number = " + number); 

調試在PHP

error_log('**********************DEBUG************************'); 
ob_start(); 
var_dump($_POST); 
$postBack = ob_get_contents(); 
ob_end_clean(); 
error_log($postBack); 
error_log('**********************DEBUG************************'); 

嘗試我的功能:

public static String apiCaller(List<NameValuePair> params, url){ 

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

    String jsonString = null; 

    try { 
     httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); 
     HttpResponse response = httpClient.execute(httpPost); 
     HttpEntity respEntity = response.getEntity(); 

     if (respEntity != null) { 
      InputStream inputStream = respEntity.getContent(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        inputStream, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      inputStream.close(); 

      jsonString = sb.toString(); 
      Log.d(LOG_TAG, jsonString); 

     } 
    } catch (UnsupportedEncodingException e) { 
     // writing error to Log 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     // writing exception to log 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // writing exception to log 
     e.printStackTrace(); 
    } 

    return jsonString; 
} 
+0

我已經登錄了,我甚至嘗試過硬編碼。該數字正在到達JSONParser。但是,這不會超越。 – Rachit

+0

@ user3286614我只是給了你一個提示,看看我的編輯 – meda

+0

我有一種感覺,「新的UrlEncodedFormEntity(params,」UTF-8「);」似乎不是在做它的工作。因爲我記錄了這條語句收到的內容,並且它們完全和它們應該是一樣的。 – Rachit