0

我正在使用 json 对象将数据从 android 发送到 php 脚本,如下所示:

            jobj.put("uname", userName);
            jobj.put("password", passWord);
            JSONObject re = JSONParser.doPost(url, jobj);

那么doPost()方法如下:

public static JSONObject doPost(String url, JSONObject c) throws ClientProtocolException, IOException 
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost request = new HttpPost(url);
        HttpEntity entity;
        StringEntity s = new StringEntity(c.toString());

        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        entity = s;
        request.setEntity(entity);
        HttpResponse response;
        try{
            Log.v("Request",""+request);
            response = httpclient.execute(request);
            //Log.v("response",""+response);
            HttpEntity httpEntity = response.getEntity();
            is = httpEntity.getContent();

        }
        catch(Exception e){ 
            Log.v("Error in response",""+e.getMessage());
            }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            //Log.v("Reader",""+reader.readLine());
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            //Log.v("response",sb.toString());
            is.close();
            json = sb.toString();
            Log.v("response",json);
        } catch (Exception e) {
            Log.v("Buffer Error", "Error converting result " + e.toString());
        }

     // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (Exception e) {
            Log.v("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;
    }

我有一个 php 脚本来验证输入,如下所示:

$response = array();
$con=mysqli_connect("localhost","user","password","manage");
if((isset($_POST['uname']) && isset($_POST['password']))){
$empid = $_POST['uname'];
$pass = $_POST['password']);

$query = "SELECT empid,password FROM master WHERE mm_emp_id='".mysql_real_escape_string($empid)."' and mm_password='".mysql_real_escape_string($pass)."'";

$result = mysqli_query($con, $query);
if($result->num_rows != 0){
    $response["success"] = 1;
    $response["message"] = "";
    print_r(json_encode($response));
}
else{
    $response["success"] = 0;
    $response["message"] = "The username/password does not match";
    print_r(json_encode($response));
}
}

问题是 isset() 没有捕获 uname 键,我得到了未定义的 'uname' 和 'password' 键的索引。如您所见,json 对象被转换为字符串并作为字符串实体添加到请求中。我无法弄清楚我做错了什么 $_post 没有收到这些值。

请就我一直在做的事情提出建议,以便我可以在我的 php 脚本中接收参数。

4

1 回答 1

0

您正在从 android 以 application/json 的形式发布数据,因此您可以通过以下方式访问 php 中的数据:

$post_data = json_decode(file_get_contents('php://input'));
于 2013-10-24T12:40:07.640 回答