【问题标题】:Receiving customized response and file from REST web services从 REST Web 服务接收自定义响应和文件
【发布时间】:2016-06-13 18:04:37
【问题描述】:

我正在尝试使用 Java 创建一些 REST Web 服务,以便发送数据、在服务器上进行计算并返回结果。在第一阶段,我以 excel 文件的形式发送和接收信息(将来我更喜欢使用 XML 或 JSON)。 好吧,经过很多小时的尝试,阅读了很多帖子,似乎我很接近实现它,但我不知道如何获得服务器的最终响应。 我有这样的服务:

@GET
@Path("/test")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFile(@QueryParam("IDfile") String IDfile) { 
    if(IDfile.trim().length() == 0 || IDfile == null) {
        return Response.status(Response.Status.BAD_REQUEST).entity("IDfile cannot be blank").build();
    }        

    String uploadedFileLocation = "C:\\FilesWebservice\\" + IDfile;
    Boolean sortida = false;
    try {
        prova prueba = new prova();
        sortida = prueba.prova(uploadedFileLocation); //this creates an xls file as response
    } catch (Exception ex) {
        System.out.println("error" + ex.toString());
        Logger.getLogger(ServiceResource.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (sortida) {
        File file = new File("C:\\FilesWebservice\\out\\prediction.xls"); // the File path you want to serve.
        return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM)
          .header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"" ) //optional
          .build();
    } else
        return Response.status(500).entity("It was unable to calculate (Ask God for the reason)").build();

}

它工作正常,如果我通过浏览器发送 GET,我会在我的下载文件夹中收到文件,但我需要使用另一个应用程序使用该服务。因此,我正在使用 Netbeans 开发一个客户端,然后,NB 根据我的 Web 服务创建了自动代码。在这种情况下,我有:

public <T> T getFile(Class<T> responseType, String IDfile) throws ClientErrorException {
    WebTarget resource = webTarget;
    if (IDfile != null) {
        resource = resource.queryParam("IDfile", IDfile);
    }
    resource = resource.path("test");

    Builder builder = resource.request(MediaType.APPLICATION_OCTET_STREAM_TYPE);
    Invocation invocation = builder.buildGet();

    return resource.request(MediaType.APPLICATION_OCTET_STREAM_TYPE).get(responseType);
}

也许我添加了一些台词,我现在不记得了。无论如何,该服务会返回一个状态代码、一条自定义消息和作为附件的文件。我想至少读取状态代码并显然保存文件,但我不知道该怎么做。 我试着做:

    MyJerseyClientAlgA client = new MyJerseyClientAlgA("192.168.1.30");
    Object response = client.getFile(Response.class, "3cphkhfu.xls");

但未能从“响应”中提取我需要的信息。 任何帮助或想法将不胜感激。

在此先感谢

编辑:

感谢@LutzHorn 的回复。我不确定我是否理解你的建议,我会做一些测试,如果我找到解决方案,我会在我的问题下发布。反正我又生成了消费REST服务的自动代码,即:

public <T> T getFile(Class<T> responseType, String IDfile) throws ClientErrorException {
    WebTarget resource = webTarget;
    if (IDfile != null) {
        resource = resource.queryParam("IDfile", IDfile);
    }
    resource = resource.path("test");
    return resource.get(responseType);
}

但我在最后一行有一个错误,它表明: 找不到符号

符号:方法get(Class)

所以我把这一行改成了

return resource.request(MediaType.APPLICATION_OCTET_STREAM_TYPE).get(responseType);

但我不确定这是否正确。

【问题讨论】:

  • 不要return resource.request,而是将其分配给局部变量。 NetBeans 将帮助您设置此变量的正确类型。然后您可以访问状态码和响应正文。

标签: java web-services rest


【解决方案1】:

好吧,经过几个小时的搜索和测试,这段代码可以工作了。我不知道这是否是最好的解决方案,但它完全符合我的要求:提取状态并保存 Web 服务返回的文件。

public void getFile(String IDfile) throws ClientErrorException {
    WebTarget resource = webTarget;
    if (IDfile != null) {
        resource = resource.queryParam("IDfile", IDfile);
    }
    resource = resource.path("test");
    Invocation inv = resource.request(MediaType.APPLICATION_OCTET_STREAM_TYPE).buildGet();
    Response rp = inv.invoke();
    InputStream attachment = null;
    try {
        if (rp.getStatus() == 200) { 
            attachment = rp.readEntity(InputStream.class); //This method can be invoked only once unless you buffer the response...
            ReadableByteChannel rbc = Channels.newChannel(attachment); //website.openStream()
            FileOutputStream fos = new FileOutputStream("C://FilesWebservice/solution.xls");
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);                
        } else {
            System.out.println(rp.getStatus());
        }
    } catch ( Exception ex) {
            ex.printStackTrace(); 
    } finally {
        rp.close();
    }

}

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-29
    • 1970-01-01
    • 2016-03-20
    • 1970-01-01
    相关资源
    最近更新 更多