这是我在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请求发送到服务器。而且,我也能收到回应。但是,我想在服务器上的POST请求中检索从android设备(客户端)发送的数据。我该如何克服这个问题?感谢。
答案 0 :(得分:1)
我已经解决了这个问题。这是服务器代码,用于检索从客户端发送到服务器端的POST数据。
@Post("json")
public Representation registerNumber(Representation entity) {
System.out.println("JsonRepresentation : " + entity);
String postContent;
try {
postContent = entity.getText();
System.out.println("POST Content : " + postContent);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
您可以使用终端中的curl测试此代码:
curl -i -X POST <your_url> -H "Content-Type: application/json" -d '{"key" : "value"}'