简体   繁体   中英

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

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(eg, "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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM