我一直在尝试开发我的简单 Spring 应用程序,但是当我收到请求时,我总是收到 400 代码,但我不知道为什么。我在下面提供了 Main、Controller 和服务类。我仔细检查了为请求提供的路径,但仍然没有任何结果。
POST http://localhost:8080/api/v2/customer
Content-Type: application/json
{
"name": "Alex",
"phoneNumber": "0756526",
"createdAt": "2022-12-17"
}
数据库实体管理器类
package com.example.greenbottle.customer;
import javax.persistence.*;
import java.time.LocalDate;
@Entity
@Table
public class Customer {
@Id
@SequenceGenerator(
name = "customer_sequence",
sequenceName = "customer_sequence",
allocationSize = 1
)
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "customer_sequence"
)
private Long id;
private String name;
private String phoneNumber;
private LocalDate createdAt;
public Customer(String name, String phoneNumber,LocalDate createdAt) {
this.name = name;
this.phoneNumber = phoneNumber;
this.createdAt = createdAt;
}
public Customer() {}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public LocalDate getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDate createdAt) {
this.createdAt = createdAt;
}
}
客户
@RestController
package com.example.greenbottle.customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(path = "api/v2/customer")
public class CustomerController {
private final CustomerService customerService;
@Autowired
public CustomerController(CustomerService customerService) {this.customerService =
customerService;}
@GetMapping
public List<Customer> getCustomers() {return customerService.getCustomers();}
@PostMapping
public void registerNewCustomer(@RequestBody Customer customer)
{customerService.registerNewCustomer(customer);}
}
还有客户
@Service
类
package com.example.greenbottle.customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.List;
import java.util.Optional;
@Service
public class CustomerService {
private final CustomerRepository customerRepository;
@Autowired
public CustomerService(CustomerRepository customerRepository) {this.customerRepository = customerRepository;}
public List<Customer> getCustomers() {
return customerRepository.findAll();
}
public void registerNewCustomer(Customer customer) {
customerRepository.save(customer);
}
}
HTTP 消息语法必须遵循协议定义,即在标头末尾和有效负载数据(正文)开始之前必须有一个空行。不这样做,将导致 HTTP 请求格式错误。
所以,你可以尝试:
POST http://localhost:8080/api/v2/customer
Content-Type: application/json
//MANDATORY EMPTY-LINE HERE
{
"name": "Alex",
...
...
}