0

I'm new using CXF and Spring to make RESTful webservices. The project is under maven control.

I have a android app that would like to connect to the server retrieving book information and cover picture via RESTful webservices. Is it possible (and how) RESTful service return an image?

Project Explorer

Project
--Java Resource
----src/main/java
------library.service
--------IBook.java
--------Book.java
----images
------Cover1.png
------Cover2.png
--JavaResources
--Deployed Resources
----webapp
------WEB-INF
----web-resources

IBook.java interface

@GET
@Path("/book/cover/{name}")
@Produces("image/png")
public Image getImage(@PathParam("name") String name);

Book.java impl

public Image getImage(String name){
    //How should I get cover png from 'images' folder and return it??
}

Thanks

Silvester Pang

4

1 回答 1

3

您可以通过 Response.ok(params...).build() 返回您选择的图像

将您的 IBook.java 更改为

    @GET
    @Path("/book/cover/{name}")
    @Produces("image/*")
    public Response getImage(@PathParam("name") String name);

还有你的实现接口。

public Response getImage(String name){
    File file = new File(fileUrl);
    String mediaType = SomeContentTypeMapHere(file)
    return Response.ok(file,mediaType).build()
}

编辑

当我们的方法处理程序被调用时,我们曾经Response.ok(Object type, String mediaType).build()构建并返回一个响应。第一个参数是一个对象。将其视为当某人/某人在给定的 url 上发送请求时我们要发送的东西,而 mediaType 基本上是我们将要进行的内容类型(例如,“图像/png、图像/jpg 等)发送。

请记住将您@Produces("image/*")的内容类型与您传递给该ok(Object entity, String mediaType方法的内容类型相匹配。

于 2013-09-21T15:44:16.217 回答