您好我使用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 回答
好的,所以将sum(score)转换为JSON看起来像:
现在我有一个问题 . 它如何发送回服务器,因为我不知道如何使用PUT ..我学到了很多教程,但我没有找到这样的东西..
您必须将计算的对象转换回JSON,然后使用POST或PUT将其发送回服务器 . 在POST中,您必须阅读发布的JSON对象 - 您可以将其作为请求参数的一部分 . 从客户端读取发布的JSON对象后,可以将其反序列化为需要保留的数据 .