编程语言
首页 > 编程语言> > 创建JAX-RS提供程序以从InputStream创建Java映像

创建JAX-RS提供程序以从InputStream创建Java映像

作者:互联网

我正在尝试创建一个image / jpeg jax-rs提供程序类,该类为基于post rest的Web服务创建一个Image.我无法提出要求以测试以下内容,最简单的测试方法是什么?

 @POST
 @Path("/upload")
 @Consumes("image/jpeg")
 public Response createImage(Image image)
 {
    image.toString(); //temp code here just to see if service gets hit
    return null;
 }

import java.awt.Image;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.imageio.ImageIO;
import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import org.springframework.stereotype.Component;


@Provider
@Consumes("image/jpeg")
@Component("ImageProvider")  //spring way to register resource
class ImageProvider implements MessageBodyReader<Image> {

    public Image readFrom(Class<Image> type,
                                Type genericType,
                                Annotation[] annotations,
                                MediaType mediaType,
                                MultivaluedMap<String, String> httpHeaders,
                                InputStream entityStream) throws IOException,
        WebApplicationException {
        Image originalImage = ImageIO.read(entityStream);
        return originalImage;
    }

    public boolean isReadable(Class<?> arg0, Type arg1, Annotation[] arg2, MediaType arg3) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}

解决方法:

如果您的提供者还实现了MessageBodyWriter,则可以使用客户端库(例如Wink Client)并使用相同的提供者来感知图像:

Wink的示例代码:

ClientConfig config = new ClientConfig();
Application application = // create application that contains ImageProvider 
config.applications(application);
RestClient restClient = new RestClient(config);
URI uri = // uri to server
Image image = // create image
restClient.resource(uri).contentType("image/jpeg").post(image);

顺便说一句,您的提供程序中存在一个错误:您必须实现isReadable方法,因此对于正确的媒体类型和类,它将返回true.

标签:rest,jax-rs,java
来源: https://codeday.me/bug/20191208/2091729.html