REST webservice获取图像?路径无效?

时间:2015-11-21 19:00:01

标签: java web-services rest

我有REST Webservice,它从系统中提供了我的文件:

@Stateless
@Path("/print")
public class PictureWebservice {

    @GET
    @Path("/startPrint")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response getFile() {

        String path = "/mypath.JPG";
      File file = new File(path);
      return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM)
          .header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"" ) //optional
          .build();
    }
}

如果我打开浏览器并输入: http://192.168.2.11:8080/rest/print/startPrint

=>一切正常,我得到了图像。

但是现在我想将我的文件放在另一台PC上: 文件文件=新文件(" http://192.168.2.11:8080/rest/print/startPrint")

但是我得到了一个错误" FileNotFoundException"。怎么了?我猜路径无效?

2 个答案:

答案 0 :(得分:0)

您可以使用像Resteasy这样的Restful Client。

    ResteasyClient client = new ResteasyClientBuilder().build();
    ResteasyWebTarget target = client.target("http://localhost:8080/rest/status");
    Response response = target.request().get();
    String value = response.readEntity(String.class);
    System.out.println(value);
    response.close();

答案 1 :(得分:0)

File不适合这种情况。

要下载图像,您至少有两种方法:

使用URL

URL url = new URL("http://192.168.2.11:8080/rest/print/startPrint");
InputStream is = new BufferedInputStream(url.openStream();

使用JAX-RS Client API

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://192.168.2.11:8080/rest")
                         .path("print")
                         .path("startPrint");
Response response = target.request().get();
InputStream is = response.readEntity(InputStream.class);

由于您有InputStream,只需将其写入文件:

Path path = Paths.get("C:/temp", "download.png");
Files.copy(is, path);