I trying to send this json data form android to php server

北城以北 提交于 2019-12-11 04:50:39

问题


I trying to send this json data form android to php server.
this my json data{email:"user111@gmail.com",password:"00000"}, any one help how the decode this json data in php server

this my php server code

<?php
$response = array();`
require_once __DIR__ . '/db_connect.php';`

 if(!isset($_POST['params'])){
 $decoded=json_decode($_POST['params'],true)
  $email=json_decode['email'];
 $pass=json_decode['password'];
 // connecting to db
 $db = new DB_CONNECT();`


$result = mysql_query("SELECT *FROM user WHERE email = $email");
 if (!empty($result)) {
    // check for empty result
    if (mysql_num_rows($result) > 0) {`

        $result = mysql_fetch_array($result);
        $this->mylog("email".$email.",password".$pass);
        if($pass==$result[password]){
        echo " password is correct";
        $response["code"]=0;
        $response["message"]="sucess";
        $response["user_id"]=$result["userid"];
        $response["firstname"]=$result["fname"];
        $response["lastname"]=$result["lname"];
        echo json_encode($response);
        }else{
        $response["code"]=3;
        $response["message"]="invalid password and email";
        echo json_encode($response);

        }

    }else {
// required field is missing
$response["code"] = 1 ;
$response["message"] = "no data found";

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

}
}else {
// required field is missing
$response["code"] = 0;
$response["message"] = "Required field(s) is missing";

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

**this my android code json praser **

     public JSONObject loginUser(String email, String password) {

    Uri.Builder loginURL2 = Uri.parse(web).buildUpon();
    loginURL2.appendPath("ws_login.php");
    JSONObject loginJSON = new JSONObject();
    try {
        loginJSON.put("email", email);
        loginJSON.put("password", password);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    JSONObject json = jsonParser.getJSONFromUrl(loginURL2.toString(),
            loginJSON);

    return json;
}

this my android json data send function

     public JSONObject getJSONFromUrl(String url, JSONObject params) {

    // Making HTTP request
    try {
        // defaultHttpClient
        // boolean status=isNetworkAvailable();
        HttpParams param = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(param, 10000);
        HttpConnectionParams.setSoTimeout(param, 10000);
        DefaultHttpClient httpClient = new DefaultHttpClient(param);
        HttpPost httpPost = new HttpPost(url);
        StringEntity se = new StringEntity(params.toString());
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
                CONTENT_TYPE_JSON));
        httpPost.setEntity(se);

        Log.d("URL Request: ", url.toString());
        Log.d("JSON Params: ", params.toString());

        HttpResponse httpResponse = httpClient.execute(httpPost);
        int code = httpResponse.getStatusLine().getStatusCode();

        if (code != 200) {
            Log.d("HTTP response code is:", Integer.toString(code));
            return null;
        } else {
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }
    } catch (ConnectTimeoutException e) {
        // TODO: handle exception

        Log.e("Timeout Exception", e.toString());
        return null;
    } catch (SocketTimeoutException e) {
        // TODO: handle exception
        Log.e("Socket Time out", e.toString());
        return null;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    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();
        jsonResp = sb.toString();

        Log.d("Content: ", sb.toString());

    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting Response " + e.toString());
        return null;
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(jsonResp);

    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON Object
    return jObj;

}

public boolean isNetworkAvailable(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    }
    return false;
}

回答1:


If $_POST['params'] is a JSON encoded string, you only have to call json_decode once, not the multiple times that you have shown.

$decoded = json_decode($_POST['params'], true);
// Decoded is now an array of the JSON data
$email = $decoded['email'];
$pass = $decoded['password'];

It should be noted that the string in your question is not valid JSON, as email and password need to be quoted, as well.

You can do live testing of the json_decode function here: http://php.fnlist.com/php/json_decode

You can validate your JSON here: http://jsonlint.com



来源:https://stackoverflow.com/questions/25449468/i-trying-to-send-this-json-data-form-android-to-php-server

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!