简体   繁体   中英

Content type 'application/json;charset=UTF-8'

Hi can anyone help me with this error when I'm sending a post request using postman here is my controller

package com.example.rba.controller;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.rba.model.Booking;
import com.example.rba.model.LoginResponse;
import com.example.rba.model.Room;
import com.example.rba.model.User;
import com.example.rba.repository.BookingRepository;
import com.example.rba.repository.RoomRepository;
import com.example.rba.repository.UserRepository;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

@RestController
@RequestMapping("/api")
public class Controller {

    @Autowired
    BookingRepository bookingRepository;
    @Autowired
    RoomRepository roomRepository;
    @Autowired
    private JavaMailSender sender;
    @Autowired
    UserRepository userRepository;

    public String generatedString = RandomStringUtils.randomAlphabetic(10);

    @GetMapping("/read")
    public List<Booking> read() {
        return bookingRepository.findAll();
    }

    @GetMapping("/rooms")
    public List<Room> room(){
        return roomRepository.findAll();
    }

    @PostMapping(path = "/createBooking/{location}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, 
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<String> create(@PathVariable(value = "location") String location,
            @Validated @RequestBody Booking book) {
        book.setStatus("reserved");
        book.setBookingCode(generatedString);

        bookingRepository.save(book);

        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
        StringBuilder sb = new StringBuilder();

        try {
            String[] array = new String[book.getAtt().size()];
            int index = array.length;
            for (Object value : book.getAtt()) {
                array[index] = (String) value;
            }
            helper.setTo(array[index]);
            sb.append("Agenda:" + " " + book.getBookingDesc()).append(System.lineSeparator());
            sb.append("When:" +  " " + book.getDateBooked() + " " + book.getStartTime() + " " + "To" + " " + book.getEndTime())
                    .append(System.lineSeparator());
            sb.append("Where:" + " " + location).append(System.lineSeparator());
            sb.append("By:" + " " + book.getBookedUser()).append(System.lineSeparator());
            sb.append("Booking code:" + " " + generatedString);
            helper.setText(sb.toString());
            helper.setSubject("Meeting");
        } catch (MessagingException e) {
            e.printStackTrace();
            return new ResponseEntity<>("Error while sending mail ..", HttpStatus.BAD_REQUEST);
        }
        sender.send(message);

        return new ResponseEntity<>("Inputs have been saved", HttpStatus.OK);
    }

    @PutMapping("/editEquip/{id}")
    public ResponseEntity<Room> edit(@PathVariable(value = "id") Long id, @Validated @RequestBody Room room) {
        Room editRoom = roomRepository.getOne(id);

        if (Objects.isNull(editRoom)) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        editRoom.setEquip(room.getEquip());

        Room newEquip = roomRepository.save(editRoom);
        return new ResponseEntity<>(newEquip, HttpStatus.OK);
    }

    @GetMapping("/getEquip")
    public List<Room> readEquip() {
        return roomRepository.findAll();
    }

    @PostMapping("/login")
    public ResponseEntity<LoginResponse> login(@Validated @RequestBody User user){
        String jwtToken = "";
        String username = user.getName();
        String password = user.getPassword();

        LoginResponse response = new LoginResponse();
        if(user.getName() == null && user.getPassword() == null || user.getName() != username && user.getPassword() != password) {
            return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
        }

        List<User> reg = 
                userRepository.findByNameAndPassword(username, password);

        jwtToken = Jwts.builder().setSubject(username).claim("info", user)
                .setIssuedAt(new Date()).signWith(SignatureAlgorithm.HS256, "secretKey")
                .compact();

        if(Objects.isNull(reg) || reg.isEmpty()) {
            response.setStatus(false);
            response.setMessage(username + " " + "doesn't exist");
            return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
        }
        else {
            response.setStatus(true);
            response.setMessage("Welcome");
            response.setToken(jwtToken);
        }

        return new ResponseEntity<>(response, HttpStatus.ACCEPTED);
    }

    @PostMapping("/register")
    private ResponseEntity<String> register(@Validated @RequestBody User user) {

        user.setPassword(generatedString);

        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
        StringBuilder sb = new StringBuilder();

        try {
            helper.setTo(user.getName());
            sb.append("Password:" + " " + user.getPassword());
            helper.setText(sb.toString());
            helper.setSubject("Registeration");
        } catch (MessagingException e) {
            e.printStackTrace();
            return new ResponseEntity<>("Error while sending mail ..", HttpStatus.BAD_REQUEST);
        }
        sender.send(message);

        userRepository.save(user);
        return new ResponseEntity<>("Registered Successfully, Please check your email for your password", HttpStatus.CREATED);
    }

}

and this is how I send my json using postman

在此处输入图片说明

and I am getting this error tried searching on how to fix it but the error is still there

"trace": "org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:225)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:158)
at

Edited: This is the header from postman

在此处输入图片说明

thanks in advance

问题解决了我在我的模型类之一中删除了 @JsonManagedReference 并且它有效但该类与我正在使用的类无关我想知道为什么

添加这个标签@PostMapping(path = "/createBooking/{location}",产生 = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)

your code will look like this.

@PostMapping(path = "/createBooking/{location}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseEntity create(@PathVariable(value = "location") String location, @Validated @RequestBody Booking book) { ...... }

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