Java noob在这里。我正在尝试按照下图开发Web服务。
将POST请求发送到REST服务器时,它们具有某些值,这些值(正在循环中从列表中读取)将插入到表(具有ID的新行)中。服务器返回HTTP 202 Accepted。
为确保创建ID为1的资源,发出GET请求,将POJO返回为Json。
最后,发送PATCH请求以更新特定列。
我编写了一个服务类,当分别调用每个API时,它会执行所有三个任务。我需要实现一些将POST请求发送到服务器时自动执行步骤2和3的功能。到目前为止,这是我的代码。
@Path("attachments")
public class FilesService {
private TiedostoService tiedostoService;
private AttachmentService attachmentService;
@GET
@Path("{id}")
@Produces({MediaType.APPLICATION_JSON})
public Response listAttachmentsAsJson(@PathParam("id") Integer attachmentId) throws Exception {
attachmentService = new AttachmentService();
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Attachment attachment = attachmentService.getAttachment(attachmentId);
String jsonString = gson.toJson(attachment.toString());
return Response.status(Response.Status.OK).entity(jsonString).build();
}
@PATCH
@Path("{id}")
@Produces({MediaType.APPLICATION_JSON})
public Response patchAttachments(@PathParam("id") Integer attachmentId) throws Exception {
attachmentService = new AttachmentService();
Integer update = attachmentService.update(attachmentId);
String jsonString = new Gson().toJson(update);
return Response.status(Response.Status.ACCEPTED).entity(jsonString).build();
}
@POST
@Produces({MediaType.APPLICATION_JSON})
public Response migrateToMinio(@Context UriInfo uriInfo) throws Exception {
Response response;
List<String> responseList = new ArrayList<>();
tiedostoService = new TiedostoService();
attachmentService = new AttachmentService();
List<Tiedosto> tiedostoList = tiedostoService.getAllFiles();
String responseString = null;
int i = 1;
for (Tiedosto tiedosto : tiedostoList) {
Attachment attachment = new Attachment();
attachment.setCustomerId(tiedosto.getCustomerId());
attachment.setSize(tiedosto.getFileSize());
Integer id = attachmentService.createNew(attachment);
if (id == 1) {
UriBuilder builder = uriInfo.getAbsolutePathBuilder();
builder.path(Integer.toString(i));
response = Response.created(builder.build()).build();
System.out.println(response);
responseString = response.toString();
}
responseList.add(responseString);
i++;
}
String jsonString = new Gson().toJson(responseList);
return Response.status(Response.Status.OK).entity(jsonString).build();
}
}
当我使用curl或postman测试各个端点时,它们按预期方式工作,但我在如何在POST之后自动执行GET和PATCH方面陷入了困境。我真的很感谢一些建议/建议/帮助。