silvester pang
silvester pang

Reputation: 3

cxf restful return image

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

Upvotes: 0

Views: 1656

Answers (1)

KyelJmD
KyelJmD

Reputation: 4732

You can return your selected image via Response.ok(params...).build()

Change your IBook.java to

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

And your Implementing Interface to this.

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

EDIT

We've used Response.ok(Object type, String mediaType).build() to Build and return a Response when our method handler is called. The First parameter is an Object. think it of as the Thing we're going to send when somebody/someones sends a request on the given url while mediaType is basically the Content type(e.g, "image/png, image/jpg and etc) of what we're going to send.

Remember to match your @Produces("image/*") to the content type you are passing on the ok(Object entity, String mediaType method.

Upvotes: 3

Related Questions