1

我使用 xbmc 服务器。我使用套接字连接到服务器并创建一个 JSON POST 请求。这是我的要求:

{
    "method": "XBMC.GetInfoBooleans",
    "id": "iPad~XBMC.GetInfoBooleans",
    "jsonrpc": "2.0",
    "params": {
        "booleans": [
            "Player.Paused",
            "Player.Playing"
        ]
    }
}

和代码:

    try {
        InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
        socket = new Socket(serverAddr, SERVERPORT);

        if (socket.isConnected()) {

            Log.d(LOG_TAG, "Connect with server");

            try {

                JSONObject jsonObjectMain = new JSONObject();
                JSONObject jsonObjectAdd = new JSONObject();
                JSONArray jsonArray = new JSONArray();

                jsonArray.put("Player.Paused");
                jsonArray.put("Player.Playing");

                jsonObjectAdd.put("booleans", jsonArray);

                jsonObjectMain.put("method", "XBMC.GetInfoBooleans");
                jsonObjectMain.put("id", "iPad~XBMC.GetInfoBooleans");
                jsonObjectMain.put("jsonrpc", "2.0");
                jsonObjectMain.put("params", jsonObjectAdd);

                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                out.write(jsonObjectMain.toString());
                out.flush();

            } catch (Exception e) {
                e.printStackTrace();
            }

            String inputLine = null;
            String result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            while ((inputLine = in.readLine()) != null) {
                Log.d(LOG_TAG, in.readLine());
                result = result.concat(inputLine);
                Log.d(LOG_TAG, result);

            }

        }

        else
            Log.d(LOG_TAG, "Unconnect");

    } catch (UnknownHostException e1) {
        e1.printStackTrace();
        Log.d(LOG_TAG, "Ошибка UnknownHostException");
    } catch (IOException e1) {
        e1.printStackTrace();
        Log.d(LOG_TAG, "Ошибка IOException");
    }

在日志中我可以看到"Connect with server",但我没有看到字符串"Result"。在 Android 清单中,我添加了所有权限。我究竟做错了什么?

谢谢!

4

1 回答 1

0

while loop您从流中读取两次。可能您只收到一行,而当您尝试阅读第二行时,您会得到 null 或End of stream. 更改while为:

while ((inputLine = in.readLine()) != null) {
    Log.d(LOG_TAG, inputLine);
    result = result.concat(inputLine);
    Log.d(LOG_TAG, result);
}

此外,作为一项改进:您应该使用StringBuilder而不是连接字符串。

于 2013-07-16T07:24:41.093 回答