这是我在 android 上的 restlet 客户端代码:
public void sendDataToServer(final JsonObject jsonObject) {
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
String jsonObjectString = jsonObject.toString();
StringEntity entity = null;
try {
entity = new StringEntity(jsonObjectString);
entity.setContentType(APPLICATION_JSON);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ClientResource clientResource = new ClientResource("http://192.168.0.101:8080/RestletDemo/register");
try {
Representation representation = clientResource.post(entity, MediaType.APPLICATION_JSON);
// representation.getJsonObject();
Response response = clientResource.getResponse();
String jsonResponse = response.getEntity().getText();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
此代码在服务器端:
@Post("json")
public String registerNumber(JsonRepresentation entity) {
String serverResponse = "Number Registered";
try {
// JsonRepresentation respresentation = new JsonRepresentation();
String response = this.getRequest().getEntity().getText();
System.out.println(response);
Gson gson = new Gson();
serverResponse = gson.toJson(serverResponse);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return serverResponse;
}
当前场景:我能够向服务器发送发布请求。此外,我也能够收到回复。但是,我想在服务器上的 POST 请求中检索从 android 设备(客户端)发送的数据。我该如何克服这个问题?谢谢。