我正在使用nkzawa's Socket.IO-client.java开发一个Android客户端,并且无法弄清楚如何通过套接字在请求主体中使用数据发出POST或PUT请求。
我已设法执行GET请求,其执行方式如下:
...
JSONObject obj = new JSONObject();
obj.put("url", "/list/subscribe/");
socket.emit("get", obj);
...
我尝试用“put”和“post”交换“get”并尝试将“data”和“body”添加到JSONObject,但没有成功。收到的请求正文在服务器上保持为空。
制作post request with data in Sails.js很容易,这正是我想用Java客户端做的事情。那可能吗?
这是一个解决方案。
JSONObject jsonObjectBody = new JSONObject();
try {
jsonObjectBody.put("sender", senderId);
jsonObjectBody.put("recipient", recipientId);
jsonObjectBody.put("message", message);
jsonObjectBody.put("shop", shopId);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject jsonObjectRequest = new JSONObject();
try {
jsonObjectRequest.put("url", "/v1/chat/client/messages");
jsonObjectRequest.put("data", jsonObjectBody);
} catch (JSONException e) {
e.printStackTrace();
}
socketInstance.emit("post", jsonObjectRequest, new Ack() {
@Override
public void call(Object... args) {
Log.e("SocketUtil", "User sent a message");
}
});
const body = req.body;