繁体   English   中英

如何获取(或识别)我的RESTAPI发送的多个数据?

[英]How can I get (or identify) multiple pieces of data sent by my RESTAPI?

我创建了以下RESTAPI:

<?PHP

//connect to database, get coins player has, then define $coins
//also get the password hash ($hash)

echo json_encode([$coins, $hash]);

?>

好吧,到目前为止一切都很好。

接下来,我的客户端(用Java编写)将读取响应。 我写了一些代码来做到这一点:

        try{
            URL url = new URL("http://example/rest.php");
            try{
                HttpURLConnection connection = (HttpURLConnection)url.openConnection();
                connection.setRequestMethod("GET");
                connection.connect();

                BufferedReader br = new BufferedReader(new InputStreamReader(
                        (connection.getInputStream())));

                String output;
                System.out.println("Output from Server .... \n");
                while ((output = br.readLine()) != null) {
                    System.out.println(output);
                }

                connection.disconnect();
            }
            catch(IOException e){
                System.out.println(e);
            }
        }
        catch(MalformedURLException e){
            System.out.println(e);
        }

当打印响应时,我与String同时获得硬币和哈希。 如何在Java中识别变量,以便实际使用它们? 我想将$coins to Integer coins = //get data的数据分配$coins to Integer coins = //get data从响应中$coins to Integer coins = //get data ,反之亦然,使用$ hash。

假设您获得有效的JSON,则应使用Gson( https://github.com/google/gson )之类的JSON解析器将您现在作为字符串读取的JSON解析为有意义的东西。

最好的方法是创建一些类来保存数据,然后让Gson将收到的数据映射到那些类型的对象。

用户指南中有大量文档和示例。 https://github.com/google/gson/blob/master/UserGuide.md

还有其他用于解析JSON的库,因此Gson只是一种选择。

在旁注中,我不太清楚密码散列如何成为json_encode方法的有效第二个参数,但是据我所知,这不是问题:)

暂无
暂无

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

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