简体   繁体   中英

POST request to Jersey Service

I am trying to call a post method while passing a json object but when I print the object it is in unitialized form.

I am doing something like curl -X POST -H 'Content-Type: application/json' -d '{"distributors":{"distributorId":"5","name":"SA"}}' {path}

Here's the Java code:

package com.rest.resource;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "distributors")
public class Distributor
   {
   @XmlElement
   private long   distributorId;
   @XmlElement
   private String name;

   public Distributor()
      {
      }

   public Distributor(final long distributorId,final String name)
      {
      this.distributorId = distributorId;
      this.name = name;
      }
   @Override
   public String toString()
      {
      return "distributors: {distributorId = " + distributorId + ", name = " + name + "}";
      }
   }

Method in the Resource

@POST
   @Path("")
   public Response addDistributor(final JAXBElement<Distributor> element)
      {
      final Distributor distributor = element.getValue();
      System.out.println(distributor);
      return Response.status(200).entity(distributor.toString()).build();
      }

Thanks.

All I did was change the return type like this:

@POST
@Path("/distpost")
@Produces(MediaType.APPLICATION_JSON)
public Response addDistributor(final Distributor distributor) {
    System.out.println(distributor);
    return Response.status(201).entity(distributor.toString()).build();
}

And it handles a curl test like this:

curl -X POST -H 'Content-Type: application/json' -d '{"distributor": {"distributorId":5,"name":"SA"}}' <url>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM