我已经被困在这部分作业上一段时间,但无济于事。我可以使用我所有的@GET方法,但不能@POST。以下是我的实现:
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Doctor createDoctor(Doctor doctor) throws Exception{
return dao.createDoctor(doctor);
}
我的道法:
public Doctor createDoctor(Doctor doctor) throws Exception {
PreparedStatement query = null;
Connection conn = null;
try {
conn = DatabaseConnection.getDataSource().getConnection();
query = conn
.prepareStatement("INSERT INTO doctor (dId, first_name, last_name, specialty, sex, experience, salary) VALUES (?,?,?,?,?,?,?)");
query.setInt(1, doctor.getId());
query.setString(2, doctor.getFirstName());
query.setString(3, doctor.getLastName());
query.setString(4, doctor.getSpecialty());
query.setString(5, doctor.getSex());
query.setInt(6, doctor.getExperience());
query.setDouble(7, doctor.getSalary());
query.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
if (conn != null)
conn.close();
}
return doctor;
}
我打电话的卷曲命令:
curl -i -X POST -H 'Content-Type:application/json' -d '{"dId":2,"first_name":"joanna","last_name":"smith","specialty":"eyebrows","sex":"female","experience":1,"salary":1.0}' http://localhost:7001/FirstRestfulService/api/medicalsystem
错误我得到了:
HTTP/1.1 415 Unsupported Media Type
Connection: close
Date: Thu, 20 Mar 2014 05:14:17 GMT
Content-Length: 22
Content-Type: text/html; charset=UTF-8
X-Powered-By: Servlet/3.0 JSP/2.2
Unsupported Media Type
得到所有医生:
@Path("/doctors")
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Doctor> getAllDoctors() throws Exception{
return dao.getAllDoctors();
}
让所有患者:
@Path("/patients")
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Patient> getAllPatients() throws Exception{
return dao.getAllPatients();
}
答案 0 :(得分:0)
用户 @FormParam 注释并尝试。
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
答案 1 :(得分:0)
希望您正在执行Windows
的请求,并且它不支持参数周围的单引号'
。请改用双引号"
。
-H "Content-Type:application/json"
对于JSON对象,也可以从内部转义双引号。例如:
-d "{\"dId\":2,\"first_name\": ... and more...}"
还要确保您的json格式正确,以便您的服务器可以解析它。
最后在curl请求中添加-v
参数,以便您可以在屏幕上看到curl的调试打印,这将对您有所帮助。