2014-04-04 82 views
0

我有以下的簽名球衣Web服務:如何將對象發佈到新澤西REST服務

@POST 
@Consumes(MediaType.APPLICATION_JSON) 
public Response save(Student a) {...} 

我想要使用org.apache.http.client在我的Java代碼POST請求。 HttpClient並傳遞一個Student對象。我怎麼能這樣做呢?我發現大量的例子將一個字符串作爲namedvaluepair發佈。但是如何發佈自定義對象還不太清楚。建議?提前致謝。

回答

0

我用這個來測試dmy,身體是JSON格式的。所以請將您的Student對象轉換爲JSON數據。

public String post(String url, HashMap<String, String>params, String body) throws Exception { 
    HttpPost postRequest = new HttpPost(url); 

    for(String key : params.keySet()){ 
     postRequest.addHeader(key, params.get(key)); 
    } 

    StringEntity input = new StringEntity(body); 
    input.setContentType("application/json"); 
    postRequest.setEntity(input); 

    HttpResponse response = (new DefaultHttpClient()).execute(postRequest); 

    if (response.getStatusLine().getStatusCode() != 200) { 
     throw new RuntimeException("Failed : HTTP error code : " 
       + response.getStatusLine().getStatusCode()); 
    } 

    BufferedReader br = new BufferedReader(
      new InputStreamReader((response.getEntity().getContent()))); 

    String output; 
    StringBuffer totalOutput = new StringBuffer(); 
    while ((output = br.readLine()) != null) { 
     totalOutput.append(output); 
    } 
    return totalOutput.toString();  
}