【问题标题】:"Unsupported Media Type" in spring boot - Windows春季启动中的“不支持的媒体类型” - Windows
【发布时间】:2019-12-05 21:09:11
【问题描述】:

我有一个像这样的User 课程:

@Data
@Entity
public class User {
    @Id
    @GeneratedValue
    Long userID;

    String eMail;

    String passwordHash;

    //ArrayList<ClassRoom>adminOf=new ArrayList<>();

    User() {}

    public User(String eMail, String passwordHash) {
        this.eMail = eMail;
        this.passwordHash = passwordHash;
    }
}

LoadDatabase 课程中我有:

@Bean
CommandLineRunner initDatabase(UserRepository userRepository) {
    return args -> {
        log.info("Preloading " + userRepository.save(new User("admin@admin.com", "asdasd")));
        log.info("Preloading " + userRepository.save(new User("admin@admin.com", "12345")));
    };
}

给我这个:

现在当我给curl -v localhost:8080/user这个命令时,它给了我这个:

这是非常正确的,虽然它给了我email 而不是eMail

但是当我给的时候

curl -X PUT localhost:8080/user/3 -H 'Content-type:application/json' -d '{"passwordHash":"12345","email":"admin1@admin.com"}'

上面写着:

这太可怕了。我正在关注this 教程。

这是我的UserController 课程:

package com.mua.cse616.Controller;


import com.mua.cse616.Model.User;
import com.mua.cse616.Model.UserNotFoundException;
import org.springframework.web.bind.annotation .*;

import java.util.List;

@RestController
class UserController {

    private final UserRepository repository;

    UserController(UserRepository repository) {
        this.repository = repository;
    }

    // Aggregate root

    @GetMapping("/user")
    List<User> all() {
        return repository.findAll();
    }

    @PostMapping("/user")
    User newUser(@RequestBody User newUser) {
        return repository.save(newUser);
    }

    // Single item

    @GetMapping("/user/{id}")
    User one(@PathVariable Long id) {

        return repository.findById(id)
                .orElseThrow(() -> new UserNotFoundException(id));
    }

    @PutMapping("/user/{id}")
    User replaceUser(@RequestBody User newUser, @PathVariable Long id) {

        return repository.findById(id)
                .map(employee -> {
                    employee.setEMail(newUser.getEMail());
                    employee.setPasswordHash(newUser.getPasswordHash());
                    return repository.save(employee);
                })
                .orElseGet(() -> {
                    newUser.setUserID(id);
                    return repository.save(newUser);
                });
    }

    @DeleteMapping("/user/{id}")
    void deleteUser(@PathVariable Long id) {
        repository.deleteById(id);
    }
}

更新后的Put方法:

@PutMapping(path="/user/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
User replaceUser(@RequestBody User newUser, @PathVariable Long id) {

    return repository.findById(id)
            .map(employee -> {
                employee.setEMail(newUser.getEMail());
                employee.setPasswordHash(newUser.getPasswordHash());
                return repository.save(employee);
            })
            .orElseGet(() -> {
                newUser.setUserID(id);
                return repository.save(newUser);
            });
}

现在有两个问题

  • 为什么是email而不是eMail,怎么办才能得到eMail而不是email
  • 如何正确POST,我做错了什么?

【问题讨论】:

  • "为什么用email 而不是eMail,怎么办才能得到eMail 而不是电子邮件" - 这就是杰克逊的行为方式。有注释,例如@JsonProperty,控制其行为。有关详细信息,请参阅this question。 --- "如何正确设置POST,我做错了什么?" - 你试过设置@PutMapping(..., consumes = MediaType.APPLICATION_JSON_VALUE, ...)吗? --- 备注:以后请限制自己在每个帖子中回答一个问题。
  • 您使用的是哪个操作系统?
  • 从下次开始,我会尽量记住这一点......我在 Windows 10 上......

标签: java spring spring-boot curl


【解决方案1】:

为什么要用email 而不是eMail”——这只是Jackson 的默认行为。

如何获取eMail 而不是email” - 您可以通过 POJO 上的注释来控制 Jackson 的行为。这里相关的是@JsonProperty。详情请见this question

如何正确POST,我做错了什么?” - 你的意思是PUT 而不是POST,不是吗?定义方法使用的内容类型:

@PutMapping(path="/user/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
User replaceUser(@RequestBody User newUser, @PathVariable Long id) {
    ...
}

另外,正如@rimonmostafiz 所指出的,您需要重新定义您的curl 调用,转义引号:

curl -X PUT -H "Content-Type: application/json" -d "{ \"email\": \"asd\", \"passwordHash\": \"sad\" }"

顺便说一句:以后请limit yourself to one question per post

【讨论】:

    【解决方案2】:

    @PutMapping 注释上添加缺少的consumes 属性,

    @PutMapping(path= "/user/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    User replaceUser(@RequestBody User newUser, @PathVariable Long id) {
    

    虽然它给了我电子邮件而不是电子邮件

    这完全取决于您的getter/setter 属性eMail 在您的User 实体中。我认为您的 getter 必须是 getEmail(),因此通常您会收到作为 JSON 属性的响应电子邮件。

    【讨论】:

    • path 设置有效但...仍然给我错误.. 请参阅here 命令是:curl -X POST localhost:8080/user -H 'Content-type:application/json' -d '{"passwordHash":"12345","email":"adminasd@admin.com"}'
    • @MaifeeUlAsad 您在错误的端点上PUTing(网址中缺少/3...)
    • 您没有使用正确的 API。您的日志显示您正在使用 API /user 和 POST 方法。您的问题是针对 /user/{id} 和 PUT。
    • PUT 也不起作用...Here 是结果...它说:"status":405,"error":"Method Not Allowed","message":"Request method 'PUT' not supported","path":"/user"
    • @MaifeeUlAsad 请详细说明并向我们展示您的确切意思
    猜你喜欢
    • 2015-12-04
    • 2019-07-02
    • 2014-05-10
    • 2019-08-02
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    相关资源
    最近更新 更多