1

これがAndroid上の私のレストレットクライアントコードです:

    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デバイス(クライアント)から送信されたデータを取得したいと思います。この問題を解決するにはどうすればよいですか?ありがとう。

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 に答える