我使用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清单中,我添加了所有权限。我做错了什么?
谢谢!
答案 0 :(得分: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
而不是连接字符串。