星期一, 7月 30, 2012

[Jersey] Client Post

Form post

MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");
ClientResponse response = webResource.type("application/x-www-form-urlencoded").post(ClientResponse.class, formData);

Post JSON
需要注意在post json要這樣使用webResource.type(MediaType.APPLICATION_JSON).post(), 否則會回傳 415 Unsupported media type
public String isExist(
   String parentUUID,
   String objName,
   String alf_ticket){
  
  String response = null;
  
  String apiURL = this.getEndpoint() + "/repo/object/check?ticket=" + alf_ticket;
  
  this.client = Client.create();
  
  //input body
  JSONObject jsonBody = new JSONObject();
  try {
   jsonBody.put("parentUUID", parentUUID);
   jsonBody.put("objName", objName);
  } catch (JSONException e) {
   System.out.println("[RepositoryObject] Fail to create json");
  }
  
  //create resource
  this.webResource = this.client.resource(apiURL);
//  this.webResource.type("application/json");
  
  //do post
  this.clientResp =  webResource.type(MediaType.APPLICATION_JSON).post(
    ClientResponse.class,jsonBody.toString());
  
  //get string of response
  response = this.clientResp.getEntity(String.class);
  
  System.out.println("[RepositoryObject] status:" + this.clientResp.getStatus());
  System.out.println("[RepositoryObject] response:" + response);
  
  return response;
 }

沒有留言:

張貼留言

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails