2014-05-13 28 views
7

Ho sviluppato un servizio Web in java utilizzando il framework dropwizard. Voglio che consumi un json.Passaggio da JSON a WebService

Il mio codice servizio è -

- Classe Resource

@Path(value = "/product") 
    public class ProductResource{ 

    @POST 
    @Path(value = "/getProduct") 
    @Consumes(MediaType.APPLICATION_JSON) 
    @Produces(MediaType.APPLICATION_JSON) 
    public Product getProduct(InputBean bean) { 
    // Just trying to print the parameters. 
    System.out.println(bean.getProductId()); 
    return new Product(1, "Product1-UpdatedValue", 1, 1, 1); 
    } 
} 

- InputBean è una classe bean semplice.

public class InputBean { 

    private int productId; 
    private String productName; 

    public String getProductName() { 
     return productName; 
    } 
    public void setProductName(String productName) { 
     this.productName= productName; 
    } 

    public int getProductId() { 
     return productId; 
    } 
    public void setProductId(int productId) { 
     this.productId= productId; 
     } 
} 

Codice Cliente -

public String getProduct() { 

      Client client = Client.create(); 
      WebResource webResource = client.resource("http://localhost:8080/product/getProduct"); 
JSONObject data = new JSONObject ("{\"productId\": 1, \"productName\": \"Product1\"}"); 
      ClientResponse response = webResource.type(MediaType.APPLICATION_JSON) 
        .accept(MediaType.APPLICATION_JSON) 
        .post(ClientResponse.class, data); 
      return response.getEntity(String.class); 
     } 

sto ricevendo un errore -

ClientHandlerException

qualcosa che non va con questo pezzo di codice?

JSONObject data = new JSONObject ("{\"productId\": 1, \"productName\": \"Product1\"}"); 
ClientResponse response = webResource.type(MediaType.APPLICATION_JSON) 
         .accept(MediaType.APPLICATION_JSON) 
         .post(ClientResponse.class, data); 

Qualcuno può indicarmi cosa potrei mancare?

diari dei clienti -

enter image description here

+0

Si prega di inviare i registri dal server. Inoltre, da dove viene la classe 'WebResource'? – chrylis

+0

Registri aggiunti ... Sto usando il framework dropwizard, è la classe di risorse da esso. – webExplorer

+0

Il registro mostra che la classe viene inviata al server come 'application/octet-stream'.Per il debug futuro, provare a utilizzare un client REST basato su browser per inviare richieste come questa manualmente per cercare di restringere il punto in cui si trova il problema. – chrylis

risposta

0

si sta impostando il tipo corretto e che fanno correttamente la richiesta.

Il problema è che non hai nulla per gestire la risposta.

A message body reader for Java class my.class.path.InputBean 

... è fondamentalmente dicendo, si sta tornando qualcosa che non può essere letto, formattata e ouputted a qualcosa di utile.

Si sta restituendo un tipo di prodotto nel servizio, che è il flusso di ottetto, ma non vedo dove si dispone di un MessageBodyWriter per l'output di questa risposta a JSON.

è necessario scaricare:

@Provider 
@Produces({ MediaType.APPLICATION_JSON }) 
public static class ProductWriter implements MessageBodyWriter<Product> 
{ 
    @Override 
    public long getSize(Product data, Class<?> type, Type genericType, Annotation annotations[], MediaType mediaType) 
    { 
     // cannot predetermine this so return -1 
     return -1; 
    } 

    @Override 
    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) 
    { 
     if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) 
     { 
      return Product.class.isAssignableFrom(type); 
     } 

     return false; 
    } 

    @Override 
    public void writeTo(Product data, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, 
         MultivaluedMap<String, Object> headers, OutputStream out) throws IOException, WebApplicationException 
    { 
     if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) 
     { 
      outputToJSON(data, out); 
     } 
    } 
    private void outputToJSON(Product data, OutputStream out) throws IOException 
    { 
     try (Writer w = new OutputStreamWriter(out, "UTF-8")) 
     { 
      gson.toJson(data, w); 
     } 
    } 
} 
+0

oh, quindi il problema è al punto in cui sto restituendo il prodotto dal metodo di servizio ?! qui -> 'return new Product (1," Product1-UpdatedValue ", 1, 1, 1);'? – webExplorer

+0

Questa classe che hai citato deve essere implementata nel codice di servizio? cosa devo dare nel codice client durante la lettura di un json? È 'response.getEntity (String.class);' corretto? – webExplorer

+0

Sto usando Jackson per la serializzazione JSON, quindi credo, non è un problema. Ho anche provato a rimuovere la funzionalità consumes usando postman e il webservice stampa un oggetto json. Bottomline, il webservice è in grado di produrre un json, ma non è in grado di consumarlo! – webExplorer

0

Sembra che JSONObject non può essere serializzato, perché nessuno scrittore messaggio è stato trovato. Perché non basta dare InputBean come input?

modificare il codice del client per:

public String getProduct() { 

     Client client = Client.create(); 
     WebResource webResource =  client.resource("http://localhost:8080/product/getProduct"); 
     InputBean data = new InputBean(1,1); // make sure there's a constructor 
     ClientResponse response = webResource.type(MediaType.APPLICATION_JSON) 
       .accept(MediaType.APPLICATION_JSON) 
       .post(ClientResponse.class, data); 
     return response.getEntity(String.class); 
    } 
0

Dropwizard préférés Jackson per JSON serializzazione & deserializzazione, nel qual caso si dovrebbe essere in grado di passare direttamente InputBean, è anche possibile specificare il tipo MIME manualmente o utilizzare l'Entità involucro, ad es

final Client client = new JerseyClientBuilder(environment) 
      .using(config.getJerseyClientConfiguration()) 
      .build("jersey-client"); 
    WebResource webResource = client.resource("http://localhost:8080/product/getProduct"); 
    InputBean data = new InputBean(1,1); 
    String response = webResource.post(String.class, Entity.json(data)); 

Vedi http://www.dropwizard.io/1.2.2/docs/manual/client.html#jersey-client per i dettagli su come creare un client Jersey configurato.