2012-12-28 3 views
21

私はJersey/Jacksonを使用して残りのAPIを作成しました。 JSONとして受け取っているPOJOに加えて、文字列トークンを受け取るように私のPOSTメソッドを調整したいと思います。複数のパラメータを指定した後のリクエストJSONとString on Jackson/Jersey JAVA

@POST 
@Path("/user") 
@Consumes(MediaType.APPLICATION_JSON) 
public Response createObject(User o, String token) { 
    System.out.println("token: " + token); 
    String password = Tools.encryptPassword(o.getPassword()); 
    o.setPassword(password); 
    String response = DAL.upsert(o); 
    return Response.status(201).entity(response).build(); 

} 

が、私はそのメソッドを呼び出すしたいのですが、何らかの理由でトークンプリントは関係なく、私がしようとするものヌルいないために:私はそうのように私の方法のいずれかを調整してきました。ここで私はPOSTリクエストを送信するために書いたクライアントコードは次のとおりです。

public String update() { 

    try { 
     com.sun.jersey.api.client.Client daclient = com.sun.jersey.api.client.Client 
       .create(); 
     WebResource webResource = daclient 
       .resource("http://localhost:8080/PhizzleAPI/rest/post/user"); 

     User c = new User(id, client, permission, reseller, type, username, 
       password, name, email, active, createddate, 
       lastmodifieddate, token, tokentimestamp); 
     JSONObject j = new JSONObject(c); 
     ObjectMapper mapper = new ObjectMapper(); 

     String request = mapper.writeValueAsString(c) + "&{''token'':,''" 
       + "dog" + "''}"; 
     System.out.println("request:" + request); 
     ClientResponse response = webResource.type("application/json") 
       .post(ClientResponse.class, request); 
     if (response.getStatus() != 201) { 
      throw new RuntimeException("Failed : HTTP error code : " 
        + response.getStatus()); 
     } 

     System.out.println("Output from Server .... \n"); 
     String output = response.getEntity(String.class); 
     setId(UUID.fromString(output)); 
     System.out.println("output:" + output); 
     return "" + output; 
    } catch (UniformInterfaceException e) { 
     return "failue: " + e.getMessage(); 
    } catch (ClientHandlerException e) { 
     return "failue: " + e.getMessage(); 
    } catch (Exception e) { 
     return "failure: " + e.getMessage(); 
    } 

} 

任意の助けいただければ幸いです。

答えて

38

これはJAX-RSが動作する方法ではありません。 POSTリクエストの本文は、注釈付きリソースメソッドの最初の引数(この場合はUser引数)にマーシャリングされます。

  1. ユーザーオブジェクトとトークンの両方を含むラッパーオブジェクトを作成します。クライアントとサーバーの間を行き来してください。
  2. トークンをURLのクエリパラメータとして指定し、サーバー側で@QueryParamとしてアクセスします。
  3. トークンをヘッダーパラメーターとして追加し、サーバー側で@HeaderParamとしてアクセスします。

例 - オプション1

class UserTokenContainer implements Serializable { 
    private User user; 
    private String token; 

    // Constructors, getters/setters 
} 

例 - オプション2

クライアント

WebResource webResource = client. 
    resource("http://localhost:8080/PhizzleAPI/rest/post/user?token=mytoken"); 

サーバー

@POST 
Path("/user") 
@Consumes(MediaType.APPLICATION_JSON) 
public Response createObject(@QueryParam("token") String token, User o) { 
    System.out.println("token: " + token); 
    // ... 
} 

例 - オプション3

クライアント

ClientResponse response = webResource 
    .type("application/json") 
    .header("Token", token) 
    .post(ClientResponse.class, request); 

サーバー

@POST 
Path("/user") 
@Consumes(MediaType.APPLICATION_JSON) 
public Response createObject(@HeaderParam("token") String token, User o) { 
    System.out.println("token: " + token); 
    // ... 
} 
+0

私はオプション1を避けることを好むだろう可能であればそれは私が望むより複雑なものを追加します。私はオプション2と3を試しましたが、トークンはnullを返します。私はそれほど疲れました:JSONObject j = new JSONObject(c); \t \t \t ObjectMapper mapper = new ObjectMapper(); \t \t \t文字列リクエスト= mapper.writeValueAsString(c)+ "&token = '12345'"; \t \t \t \t \t System.out.println( "request:" + request); \t \t \t ClientResponse response = webResource.type( "application/json") – sgoldberg

+3

オプション2と3を実装する方法の例を追加しました – Perception

+0

ありがとうございました!それは完璧に働いた!オプション3ありがとう! – sgoldberg

0

ジャージー1を使用している場合。X、最善のアプローチは、@FormParamとして複数のオブジェクトを投稿する

少なくとも二つの利点です:

    あなたは
  1. パラメータは複数のパラメータを投稿するラッパーオブジェクトを使用する必要はありません
  2. @QueryParam@PathParamのように)体内ではなく、URLで送信

チェックこの例:

クライアント:(ピュアJava):

public Response testPost(String param1, String param2) { 
    // Build the request string in this format: 
    // String request = "param1=1&param2=2"; 
    String request = "param1=" + param1+ "&param2=" + param2; 
    WebClient client = WebClient.create(...); 
    return client.path(CONTROLLER_BASE_URI + "/test") 
      .post(request); 
} 

サーバー:

@Path("/test") 
@POST 
@Produces(MediaType.APPLICATION_JSON) 
public void test(@FormParam("param1") String param1, @FormParam("param2") String param2) { 
    ... 
}