从Android应用程序发送和接收json到PHP脚本?

时间:2013-10-24 08:24:22

标签: php android mysql json http

我是Android开发的新手,我正在尝试创建一个登录页面,将密码和用户名作为json数组发送到php脚本,php脚本返回一个json数组响应,其中包含相应的meassage。

我已经制作了一个Android代码:

            jobj.put("uname", userName);
            jobj.put("password", passWord);
            JSONObject re = JSONParser.doPost(url, jobj);
            Log.v("Received","Response received . . ."+re);
            // Check your log cat for JSON reponse
            Log.v("Response: ", re.toString());
            int success = re.getInt("success");
            if (success == 1) {
                return 1;
            }
            else{
                return 0;
            }
        }
        catch(Exception e){ e.getMessage(); }
    }

JsonParser 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);
        Log.v("entity",""+entity);
        HttpResponse response;
        try{
            response = httpclient.execute(request);
            Log.v("REceiving","Received . . .");
            HttpEntity httpEntity = response.getEntity();
            is = httpEntity.getContent();
            Log.v("RESPONSE",""+is);
        }
        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) {
                 Log.v("line",""+line);
                sb.append(line + "\n");
            }
            Log.v("builder",""+sb);
            is.close();
            json = sb.toString();

        } 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 (JSONException e) {
            Log.v("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;
    }

}

我有php脚本:

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

$pass = $_POST['password'];
$query = "SELECT mm_emp_id,mm_password FROM employee_master WHERE mm_emp_id='$empid'and mm_password='$pass'";
$result = mysqli_query($con, $query);
if(count($result) > 0){
    $response["success"] = 1;
    $response["message"] = "";
    echo json_encode($response);
}
else{
    $response["success"] = 0;
    $response["message"] = "The username/password does not match";
    echo json_encode($response);
}
}

我在检查isset()的行处获得未定义索引。我在php脚本中接收json时做错了什么?

如果你能看到我使用link作为我的帮助 请帮帮我。

2 个答案:

答案 0 :(得分:0)

在doPost方法中,您不使用包含变量的JSON对象(JSONobject c)

答案 1 :(得分:0)

public class JSONTransmitter extends AsyncTask<JSONObject, JSONObject, JSONObject> {

String url = "http://test.myhodo.in/index.php/test/execute";

@Override
protected JSONObject doInBackground(JSONObject... data) {
    JSONObject json = data[0];
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);

    JSONObject jsonResponse = null;
    HttpPost post = new HttpPost(url);
    try {
        StringEntity se = new StringEntity("json="+json.toString());
        post.addHeader("content-type", "application/x-www-form-urlencoded");
        post.setEntity(se);

        HttpResponse response;
        response = client.execute(post);
        String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());

        jsonResponse=new JSONObject(resFromServer);
        Log.i("Response from server", jsonResponse.getString("msg"));


    } catch (Exception e) { e.printStackTrace();}

    return jsonResponse;
}

主要活动

    try {
                JSONObject toSend = new JSONObject();
                toSend.put("msg", "hello");

                JSONTransmitter transmitter = new JSONTransmitter();
                transmitter.execute(new JSONObject[] {toSend});

            } catch (JSONException e) {
                e.printStackTrace();
        }