【问题标题】:Get json info direct back from post request从 post 请求中直接获取 json 信息
【发布时间】:2014-01-03 11:52:25
【问题描述】:

我正在尝试使用 php + mysql 数据库/java for android 制作一个简单的登录系统。 两个即时通讯使用Json。

我在这里有 php 代码:(我想要归档的一个简单示例)。

    <?php
     include("../dbfunctions.php");

    class mobilelogin{
    private $user;
    private $pass;

    public function getData(){
        $get->user = $_POST['user'];
        $get->pass = $_POST['pass'];
        return $get;
    }
    public function getDbData($user){
        $dbfunctions = new dbfunctions;
        $getvalue = $this->getData();
        return $dbfunctions->returnUser($user); // get pass by user
    }
    public function md5convert($user){
        return md5($this->getDbData($user)); // convert this pass to md5
    }
    public function check(){ // check everthing here
        $getvalue = $this->getData();
        if(isset($getvalue->user) && isset($getvalue->pass)) // everthing filled in
        {
            return "valid";
        }else{
            return "invalid";
        }

    }
    public function response(){ // show data here in json format
        echo json_encode(array('result' => $this->check()));
    }

}
   header("Content-Type: text/json");
   $mobilelogin = new mobilelogin;
   echo $mobilelogin->response();
?>

如您所见,我只尝试了一个简单的 json 帖子示例, 我在 json 中的结果是这样的:{ result:invalid } 如您所见,如果 php 代码从 java 接收到 post 值,它应该显示有效,否则无效。

现在我有了这个 android 代码,它执行一个 post 请求:

public void login(View v) throws ClientProtocolException, URISyntaxException, IOException, JSONException
    {       

        HttpPost httppost = new HttpPost(processUrl);

        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
               nameValuePairs.add(new BasicNameValuePair("user", uservalidated));
               nameValuePairs.add(new BasicNameValuePair("pass", passvalidated));

               httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
               client.execute(httppost);

               Toast.makeText(getBaseContext(),"Everthing well.",Toast.LENGTH_LONG).show();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.e("testnow", response());
    }

这会在您单击登录按钮时触发发布请求,并且 php 服务器应该会收到它, 就像你看到的 Log (Log.e("testnow", response());) 是通过 httpget 接收数据的函数,这个函数:

public String response() throws URISyntaxException, ClientProtocolException, IOException, JSONException{

    HttpGet request = new HttpGet();
    request.setURI(new URI(processUrl));
    HttpResponse response;

    response = client.execute(request);
    BufferedReader in = new BufferedReader(new InputStreamReader(response
            .getEntity().getContent()));

    StringBuilder builder = new StringBuilder();
    String line;
    while((line=in.readLine())!=null)
    {

        builder.append(line);
    }
    String JSONdata = builder.toString();
    JSONObject jObject = new JSONObject(JSONdata);
    String JSONresponse = jObject.getString("result");


    return JSONresponse;
}

这从 json 输出中显示无效。但它应该显示有效,当我在用户名和密码中打勾时,它不会更新。

希望您能理解我的问题,并欢迎所有帮助。 另外,如果这不是以这种方式制作登录系统的正确方法,也请分享。

【问题讨论】:

    标签: java php android mysql json


    【解决方案1】:

    虽然我是一名 Android 应用程序开发人员,但正如你所说,我已经解决了很多问题。根据我早期的观点,我认为Android端没有问题,这是PHP端的问题。在您的服务器端代码中,此代码不会更新数据。请验证您的代码。请看PHP端的这段代码,这样你可以创建和更新代码。

    <?php
    /*
     * Following code will create a new profile row
     * All profile details are read from HTTP Post Request
     */
    // array for JSON response
    $response = array();
    // check for required fields
    if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['mobile']) && isset($_POST['gender'])&& isset($_POST['location'])  && isset($_POST['image']) && isset($_POST['fb_user']) && (trim($_POST['name']) != '') && (trim($_POST['email']) != '')  &&  (trim($_POST['mobile']) != '')  &&  (trim($_POST['gender']) != '')  &&  (trim($_POST['location']) != '')  &&  (trim($_POST['image']) != '')  ) {
    
        $name = $_POST['name'];
        $email = $_POST['email'];
        $mobile = $_POST['mobile'];
        $gender = $_POST['gender'];
        $country = $_POST['country'];
        $location = $_POST['location'];
        $image = $_POST['image'];
        $fb_user = $_POST['fb_user'];
        if($fb_user == '0'){
            $pin = $_POST['pin'];
        } else{
            $pin = '0';
        }
        $created_date = date("Ymd");
        $created_date2 = time();
        $binary=base64_decode($image);
        // binary, utf-8 bytes
    
        // include db connect class
        require_once  'db_connect.php';
        // connecting to db
        $db = new DB_CONNECT();
    
        $chk_existing_user = "SELECT * FROM `user_profile` WHERE `email` ='".$email."'";
        $res_existing_user = mysql_query($chk_existing_user);
        $num_rows_existing_user = mysql_num_rows($res_existing_user); //checking for existing user
    
       // mysql inserting a new row
        header('Content-Type: image/jpg; charset=utf-8');
        $username_arr = explode("@",$email);
        $username = $username_arr[0].'_'.$created_date;
        $file_name = 'user_images/'.$username.'.jpg';
        $file = fopen($file_name, 'wb');
        fwrite($file, $binary);
        fclose($file);
    
        if($num_rows_existing_user == 0){
            $result = mysql_query("INSERT INTO `user_profile`(name,  email, mobile, gender, country, location, image, pin, fb_user, created_date ) VALUES('$name', '$email' , '$mobile', '$gender' , '$country', '$location' , '$file_name', '$pin', '$fb_user', '$created_date')");
            $inserted_edited = '1';
        }else{
            $result = mysql_query("UPDATE `user_profile` SET name='$name', mobile ='$mobile', gender ='$gender', country='$country', location ='$location', image = '$file_name', pin = '$pin', fb_user ='$fb_user', created_date ='$created_date2' WHERE email = '$email'");
            $inserted_edited = '2';
        }
        // check if row inserted or not
        if ($inserted_edited == '1') {
            // successfully inserted into database
            $response["success"] = 1;
            $response["message"] = "profile successfully created!";
            // echoing JSON response
            echo json_encode($response);
        } else if($inserted_edited == '2') {
            // failed to insert row
            $response["success"] = 2;
            $response["message"] = "profile updated successfully!";
    
            // 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);
    }
    ?>
    

    如果我的回答对你有帮助,别忘了支持我的回答。 :)

    享受!!!

    【讨论】:

    • Thnx,我会再次研究它,但现在在 php 方面!
    • 好的,请告诉我。
    • 这不是我做的任何其他事情。但是我改变了一些东西,我现在使用我的 check() 作为对结果进行编码的基础,而不是响应函数。我在想它没有做 $_POST 也许如果我做了回应。但它仍然无法正常工作......如果它收到 $_POST 的话,我想知道,但我有另一个示例代码,它可以正常工作..
    猜你喜欢
    • 1970-01-01
    • 2015-04-27
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 2016-01-28
    • 2018-11-14
    相关资源
    最近更新 更多