2013-12-15 61 views
0

您好我已經使用Jersey和Tomcat創建了簡單的REST體系結構。我從服務器(作爲使用「/ get」的資源)發送數據給客戶端,然後客戶對這些數據進行一些計算。我的問題是,如何將這個計算的數據從客戶端發送到服務器(我想我必須使用PUT(更新資源),但我不知道如何,它根本不工作..)?更新REST中的資源,將數據發送回服務器

OK,我寫的是這樣的(服務器,包含資源)

@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服務的簡單分佈式編程。一個主人和三個奴隸。 如果有人幫助我,我將不勝感激。

回答

0

您必須將計算的對象轉換回JSON,然後使用POST或PUT將其發送回服務器。在POST中,您必須閱讀發佈的JSON對象 - 您可以將它作爲請求參數的一部分。從客戶端讀取已發佈的JSON對象後,您可以將其反序列化回需要保留的數據。

0

OK,所以轉換總和(得分),以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 ..我學到了許多教程,但我沒有找到像這樣的東西..

相關問題