从帖子请求直接获取json信息

时间:2014-01-03 11:52:26

标签: java php android mysql json

我试图用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代码,它发出了一个帖子请求:

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());
    }

单击登录按钮时会发出post请求,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输出显示无效。但是当我在用户名和密码中勾选时,它应该显示有效,但它不会更新。

我希望你理解我的问题,欢迎所有的帮助。 如果这不是以这种方式建立登录系统的正确方法,也请分享。

1 个答案:

答案 0 :(得分:2)

虽然我是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);
}
?>

如果我的回答对您有所帮助,那么请不要忘记支持我的回答。 :)

享受!!!