1

这是我在 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 设备(客户端)发送的数据。我该如何克服这个问题?谢谢。

4

1 回答 1

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"}'

于 2012-11-16T16:10:13.890 回答