0

I have java EE project.I used Spring Hibernate for server side and Backbone,RequireJS,Jquery for client side on this project.I'm trying to save with POST method but HTTP 415 Error return.

My Get method works fine. I tested it on Postman.

My url: localhost:8080/rest/travel

EDITED

My Resource Class

    @Component
@Path("/travel")
public class TravelResource {

        @Autowired
        private TravelService travelService;
       @Autowired
      private UserService userService;

    @POST
    @Produces(MediaType.APPLICATION_JSON+ ";charset=UTF-8")
    @Consumes(MediaType.APPLICATION_JSON)
        public TravelDTO save(TravelDTO dto) {
        dto.setUser(userService.get(dto.getUser().getUserID()));
          dto.setTravelStart(new Date());
          dto.setTravelEnd(new Date());

          return travelService.save(dto);
        }

    @PUT
    @Path("/{travelID}")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
        public TravelDTO edit(@PathParam("travelID") int id, TravelDTO dto) {
        dto.setUser(userService.get(dto.getUser().getUserID()));
        dto.setTravelStart(new Date());
        dto.setTravelEnd(new Date());

        return travelService.edit(id,dto);
        }

    @DELETE
    @Path("/{travelID}")
    @Produces(MediaType.TEXT_PLAIN)
        public int delete(@PathParam("travelID") int id) {
        travelService.delete(id);
        return id;
        }
    @GET
    @Path("/{travelID}")
    @Produces(MediaType.APPLICATION_JSON)
        public TravelDTO get(int id) {
        return travelService.get(id);
        }
    @GET
    @Produces(MediaType.APPLICATION_JSON)
        public List<TravelDTO> getAll() {
        return travelService.getAll();

        }

    @GET
    @Path("/search/{travelStart}/{travelEnd}/" )
    @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8")
    public List<TravelDTO> search(@PathParam("travelStart") Date travelStart,
                                  @PathParam("travelEnd") Date travelEnd )
    {
        return travelService.search(travelStart,travelEnd);
    }

}

My DTO Class

public class TravelDTO implements Serializable {

    public TravelDTO convert(Travel model) {
        this.setTravelID(model.getTravelID());
        this.setTravelCost(model.getTravelCost());
        this.setTravelStart(model.getTravelStart());
        this.setTravelEnd(model.getTravelEnd());
        this.setLocation(model.getLocation());
        this.setTravelPurpose(model.getTravelPurpose());
       this.setProjectCode(model.getProjectCode());
       this.setUser(new UserDTO().convert(model.getUser()));
        return this;
    }
        private int travelID;

       private String projectCode;

        private Date travelStart;

        private Date travelEnd;

        private String Location;

        private float travelCost;

        private UserDTO user;

        private String travelPurpose;

    public UserDTO getUser() {
        return user;
    }

    public void setUser(UserDTO user) {
        this.user = user;
    }

    public String getProjectCode() {
        return projectCode;
    }

    public void setProjectCode(String projectCode) {
        this.projectCode = projectCode;
    }

    public int getTravelID() {
            return travelID;
        }

        public void setTravelID(int travelID) {
            this.travelID = travelID;
        }

        public Date getTravelStart() {
            return travelStart;
        }

        public void setTravelStart(Date travelStart) {
            this.travelStart = travelStart;
        }

        public Date getTravelEnd() {
            return travelEnd;
        }

        public void setTravelEnd(Date travelEnd) {
            this.travelEnd = travelEnd;
        }

        public String getLocation() {
            return Location;
        }

        public void setLocation(String location) {
            Location = location;
        }

        public float getTravelCost() {
            return travelCost;
        }

        public void setTravelCost(float travelCost) {
            this.travelCost = travelCost;
        }

        public String getTravelPurpose() {
            return travelPurpose;
        }

        public void setTravelPurpose(String travelPurpose) {
            this.travelPurpose = travelPurpose;
        }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        TravelDTO travelDTO = (TravelDTO) o;

        return travelID == travelDTO.travelID;
    }

    @Override
    public int hashCode() {
        return travelID;
    }
}

MY SERVICE CLASS

@Service
public class TravelService {
        @Autowired
        private TravelDAO travelDAO;

        @Transactional
        @ResponseBody
        public TravelDTO save(TravelDTO dto) {
            Travel station = new Travel();
            station.convert(dto);
            try {
                station = travelDAO.persist(station);
            } catch (Exception e) {
                return null;
            }
            return dto.convert(station);
        }

        @Transactional
        @ResponseBody
        public TravelDTO edit(int id, TravelDTO dto) {
            Travel travel = new Travel();
            try {
                travel.convert(dto);
                travelDAO.merge(travel);
            } catch (Exception e) {
                return null;
            }
            return dto.convert(travel);
        }

        @Transactional
        @ResponseBody
        public boolean delete(int id) {
            try {
                Travel travel = travelDAO.find(id);
                travelDAO.remove(travel);
            } catch (Exception e) {
                return false;
            }
            return true;
        }

        public TravelDTO get(int id) {
            Travel travel;
            try {
                travel = travelDAO.find(id);
            } catch (Exception e) {
                return null;
            }
            return new TravelDTO().convert(travel);
        }

        public List<TravelDTO> getAll() {
            List<TravelDTO> travelDTOList = new ArrayList<TravelDTO>();
            try {
                for (Travel travel : travelDAO.findAll())
                    travelDTOList.add(new TravelDTO().convert(travel));
            } catch (Exception e) {
                return null;
            }
            return travelDTOList;
        }

        public List<TravelDTO> search(Date startTime, Date endTime)
                                      {
            List<TravelDTO> travelDTOList = new ArrayList<TravelDTO>();
            try {
                for (Travel station : travelDAO.search(startTime, endTime))
                    travelDTOList.add(new TravelDTO().convert(station));
            } catch (Exception e) {
                return null;
            }
            return travelDTOList;
        }




}

My data :

model:{"Location":"s","projectCode":"51","travelPurpose":"s","travelStart":"1.1.1","travelEnd":"8.12.2016"}

Network TAB

enter image description here

real
  • 53
  • 1
  • 2
  • 9
  • 415 Unsupported Media Type The request entity has a media type which the server or resource does not support. For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format. can you post the message which is being sent? – Moshe Arad Apr 11 '17 at 20:05
  • Added my post data @MosheArad – real Apr 11 '17 at 20:21
  • You should add the DTO object structure here. Model class is not required. – gaganbm Apr 11 '17 at 21:22
  • @gaganbm added dto and service – real Apr 11 '17 at 21:26
  • I have added the answer. You can try through curl or postman, and set proper headers. – gaganbm Apr 11 '17 at 21:31
  • I added Context-Type:application/json to header on postman and post data.Error changed now 500 @gaganbm – real Apr 11 '17 at 21:51
  • May be it is a typo at your end. It is not `Context-type`, it is `Content-type`. Secondly, 500 could mean anything, like it is not able to save it in the database, or may be a null pointer exception somewhere! But the original problem of `415 media type` seems to be solved. – gaganbm Apr 11 '17 at 21:58
  • no, if i add "Context-Type:application/json" to postman header, 415 error solved.But my code still 415 error @gaganbm – real Apr 11 '17 at 22:04
  • What is `Context-Type` ? It should be `Content-Type`. – gaganbm Apr 11 '17 at 22:10
  • And if it is getting solved from `postman`, and you are still seeing the 415 error, then it must be a problem in the client that you are using. Your javascript client or curl or whatever. – gaganbm Apr 11 '17 at 22:12
  • writing mistake sorry @gaganbm – real Apr 11 '17 at 22:13
  • Like I said, if 415 error is gone from postman, but it is coming from any other client, you need to check how you are sending the request headers. – gaganbm Apr 11 '17 at 22:16

5 Answers5

3

If you are trying the call in POSTMAN add Content-Type: application/json as header parameter.

Ravinda Lakshan
  • 1,006
  • 14
  • 14
1

HTTP 415 comes when

The origin server is refusing to service the request because the payload is in 
a format not supported by this method on the target resource.

Ref : https://httpstatuses.com/415

You need to set the request header correctly. As per the image you have attached, you are passing Content-Type: application/x-www-form-urlencoded. But your code expects application/json.

gaganbm
  • 2,663
  • 3
  • 24
  • 36
1

My error's reason is this backbone code:

Backbone.emulateJSON = true;

If Backbone.emulateJSON=true , Content-Type= application/x-www-form-urlencoded.

Now Backbone.emulateJSON=false; Problem is solved!

T J
  • 42,762
  • 13
  • 83
  • 138
real
  • 53
  • 1
  • 2
  • 9
0
    @POST
    @Produces(MediaType.APPLICATION_JSON+ ";charset=UTF-8")
    @Consumes(MediaType.APPLICATION_JSON)
        public TravelDTO save(TravelDTO dto) {
        dto.setUser(userService.get(dto.getUser().getUserID()));
          dto.setTravelStart(new Date());
          dto.setTravelEnd(new Date());

          return travelService.save(dto);
        }

you're returning: return travelService.save(dto);

and you declared that you're returning an HTTP JSON,

then just add to your controller the annotation @RestController instead of @Controller.

or just add to your method the @ResponseBody annotation.

Moshe Arad
  • 3,587
  • 4
  • 18
  • 33
  • I'm using Rest.So i have no controller class.I have just (model, service, resource,dao and dto) But i am added @ResponseBody to the POST method but same 415 error continued – real Apr 11 '17 at 20:53
  • What do you mean "I have no controller"? if you don't use controllers with Spring how do you expect from your server to receive requests from end users? – Moshe Arad Apr 11 '17 at 20:55
  • https://gist.github.com/berat703/1b54549eecfc4e09534fe1b24e824591 .My Service class expect from my server to receive requests form end users.Should i do delete "@Service" and add "@RestController" ? – real Apr 11 '17 at 21:12
  • i don't find the solution.Sorry for disturb :( – real Apr 11 '17 at 22:12
0

add following to your maven please:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson2.version}</version>
    </dependency>
vincent zhang
  • 444
  • 5
  • 20