在REST中更新资源,将数据发送回服务器

时间:2013-12-15 00:12:36

标签: java json rest

您好我使用Jersey和Tomcat创建了简单的REST架构。我将数据从服务器(作为资源使用“/ get”)发送到客户端,然后客户对此数据进行一些计算。我的问题是,如何将这个计算数据从客户端发送到服务器(我想我必须使用PUT(更新资源),但我不知道如何,它根本不起作用..)?

好的,我写的是这样的(服务器,包含资源)

@Path("/resource/{id}")
public class SimplyHello {

@GET    
@Produces(MediaType.APPLICATION_JSON)
public JSONObject sayJSONHello(@PathParam("id")String id) {
    JSONArray numbers = new JSONArray();

    int [] myNumbers = new int [1000];

    for ( int i = 0 ; i <1000 ; i++)
        myNumbers[i] = i;

    for (int i = 0; i < myNumbers.length; ++i) 
     numbers.put(myNumbers[i]);     

    JSONObject result = new JSONObject();

    try {
        result.put("numbers", numbers);
    } catch (JSONException e) {         
        e.printStackTrace();
    }                       
    return result;              
}

客户端(我对数据执行某些操作)

ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());     

   String jsonString = service.path("rest").path("resource").path("1").accept(MediaType.APPLICATION_JSON).get(String.class);
JSONObject obj = new JSONObject(jsonString);

    JSONArray array = obj.optJSONArray("numbers");

    if (array == null) { /*...*/ }

    int[] numbers = new int[array.length()];

    for (int i = 0; i < array.length(); ++i) {
        numbers[i] = array.optInt(i);
    }       

     int sum=0;

      for (int i =0 ; i <array.length() ; i++)
      {
          sum= numbers[i]+sum;                   
      }                  

我的问题是:如何将此计算数据发送回服务器?我需要比较两次:从发送数据到接收数据,以及没有sendind数据的时间计算。这将是基于REST服务的简单分布式编程。一个主人和三个奴隶。 如果有人帮助我,我将不胜感激。

2 个答案:

答案 0 :(得分:0)

您必须将计算出的对象转换回JSON,然后使用POST或PUT将其发送回服务器。在POST中,您必须阅读发布的JSON对象 - 您可以将其作为请求参数的一部分。从客户端读取发布的JSON对象后,可以将其反序列化为需要保留的数据。

答案 1 :(得分:0)

好的,所以将sum(得分)转换为JSON看起来像:

JSONObject result = new JSONObject();
      JSONObject score = new JSONObject();
      score.put("id", sum);

      try {
            result.put("id", sum);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

现在我遇到了问题。它如何发送回服务器,因为我不知道如何使用PUT ..我学习了许多教程,但我没有找到这样的东西..

相关问题