简体   繁体   English

用PHP中的json对象响应http获取请求

[英]respond to http get request with json object in php

I have a PHP page (test.php) that has to respond to a HTTP GET request sent from an android application. 我有一个PHP页面(test.php),该页面必须响应从android应用程序发送的HTTP GET请求。 The response has to be via a json object. 响应必须通过json对象。 How do I do that? 我怎么做?

For reference :- Below is a php code that checks the login details from a login form. 供参考:-下面是一个PHP代码,用于检查登录表单中的登录详细信息。 The http request would be the username and password sent from an android application that contains the login form. http请求是从包含登录表单的android应用程序发送的用户名和密码。 The response from this page would be the success or failure message. 该页面的响应将是成功或失败消息。

<?php
        session_start();
         require('connect.php');
        if (isset($_GET['username']) and isset($_GET['password']))
        {
            $username = $_GET['username'];
            $password = $_GET['password'];
            $query = "SELECT * FROM `staff_reg` WHERE username='$username' and password='$password'";

            $result = mysql_query($query) or die(mysql_error());
            $count = mysql_num_rows($result);
            if ($count == 1)
            {
                $_SESSION['username'] = $username;
            }
            else
            {
                echo "Invalid Username or Password";
            }
        }
        if (!isset($_SESSION['username']))
        {
            echo "Session Expired";
            echo "<br><a href='staff_login.php'>Click here</a> to login again"; 
            echo "<br><a href='index.html'>Click here</a> to go back to the homepage"; 
            $username = $_SESSION['username'];
        }
        else{
            $username = $_SESSION['username'];
            echo "<p>Welcome ".$username."<br>";
            echo "This is the Staff Portal<br>";
            echo "<a href='logout.php'>Logout</a></p>"; 
    ?>

I think it may help you.. 我认为这可能对您有帮助。

<?php
        session_start();
         require('connect.php');
        //create an variable $response
        //Use GET instead of POST since you are sending data in GET method
        if (isset($_GET['username']) and isset($_GET['password']))
        {
            $username = $_GET['username'];
            $password = $_GET['password'];
            $query = "SELECT * FROM `staff_reg` WHERE username='$username' and password='$password'";

            $result = mysql_query($query) or die(mysql_error());
            $count = mysql_num_rows($result);
            if ($count == 1)
            {
                $response="Success";
            }
            else
            {
                $response="Failure";
            }
        //now echo it as an json object
            echo json_encode($response);
        }

You can send your response as json encoded data eg lets say your response data is 您可以将响应作为json编码数据发送,例如,假设您的响应数据为

$user = array('firstName' =>'abc', 'lastName' =>'xyz'); 
$response = json_encode($user);

If this is an api for the android app you mentioned then you cannot use sessions in it. 如果这是您提到的android应用程序的api,则无法在其中使用会话。 You have to find another way for authorizing the user. 您必须找到另一种授权用户的方式。

You can encode your strings and arrays in json format but you'd better make an object and encode it. 您可以将字符串和数组编码为json格式,但最好创建一个对象并对其进行编码。 That way you can access the values by the name you specified in the api. 这样,您可以通过在api中指定的名称访问值。

For example: 例如:

$obj->status = "error";

Or 要么

$obj->status = "success";

And in the end: 最后:

echo json_encode($obj);

And you can access it in the application with this format: 您可以使用以下格式在应用程序中访问它:

   //String response = httpResponse
   JsonObject object = new JsonObject(response);
   String status = object.getString("status");
   if(status.equals("error")){
        //handle the error
   } else {
        //login was successful and you can show the user the proper activity
   }

As for sending the request to the api i recommend you to use the library AQuery . 至于将请求发送到api,我建议您使用库AQuery

The library can simplify your work with http requests. 该库可以简化使用http请求的工作。 it works as follows: 它的工作方式如下:

    AQuery aq = new AQuery(context);
    aq.ajax(url, JsonObject.class, new AjaxCallback<JsonObject>(){
    @Override
    public void callback(String url, JSONObject object, AjaxStatus status) {
        //object is the json object sent from the server
    }
    });

I hope this helps you 我希望这可以帮助你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM