![](/img/trans.png)
[英]Spring Boot com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Recipe'
[英]Spring Boot com.fasterxml.jackson.core.JsonParseException: Unrecognized token
我使用的是Spring Boot項目,我想在程序啟動后執行多個POST
請求,而不是事后手動使用cURL。 目的是在存儲器中存儲一些數據,並使平台為進一步操作做好准備。 我使用的原始cURL
命令(效果很好),
$ curl -i -X POST -H "Content-Type:application/json" -d "{\"name_of_doctor\" : \"Monika2\", \"price\": \"12.5\"}" http://localhost:8080/api/v1/appointments/createAppointment
需要它的API,
@PostMapping(value = "/createAppointment", consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
public ResponseEntity<Appointment> create(@RequestBody Appointment appointment) {
java.sql.Date date = new java.sql.Date(Calendar.getInstance().getTime().getTime());
java.sql.Time time = new java.sql.Time(Calendar.getInstance().getTime().getTime());
appointment.setAppointment_date(date);
appointment.setCraeted_at(time);
// we create the appointment, because, the doctor is available
appointment.setStatus(new Status(true));
// appointment.setStatus(true);
service.save(appointment);
return ResponseEntity.status(HttpStatus.CREATED).body(appointment);
}
現在,我在加載了Spring Boot之后就做好了,
@SpringBootApplication
@EnableTransactionManagement
public class AppointmentApplication {
public static void main(String[] args) {
System.out.println("\n\nAppointment Manager\n\n");
SpringApplication.run(AppointmentApplication.class, args);
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost("http://localhost:8080/api/v1/appointments/createAppointment");
List<NameValuePair> arguments = new ArrayList<>(2);
arguments.add(new BasicNameValuePair("name_of_doctor", "Monika"));
arguments.add(new BasicNameValuePair("price", "12.5"));
try {
post.setEntity(new UrlEncodedFormEntity(arguments));
//post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
HttpResponse response = client.execute(post);
System.out.println(EntityUtils.toString(response.getEntity()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
我收到以下錯誤消息:
{"timestamp":"2019-02-09T06:45:36.393+0000","status":400,"error":"Bad Request","message":"JSON parse error: Unrecognized token 'name_of_doctor': was expecting 'null', 'true', 'false' or NaN; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'name_of_doctor': was expecting 'null', 'true', 'false' or NaN\n at [Source: (PushbackInputStream); line: 1, column: 16]","path":"/api/v1/appointments/createAppointment"}
在這種情況下,如何為POST調用正確設置媒體數據?
以下代碼將值添加為請求參數。
post.setEntity(new UrlEncodedFormEntity(arguments));
考慮到您的API在請求正文中需要JSON
內容,您需要使用StringEntity
而不是UrlEncodedFormEntity
post.setEntity(new StringEntity("{ \"name_of_doctor\": \"\", \"price\": \"12.5\" }", Charset.forName("UTF-8")));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.