2011-04-27 76 views
3

我想創建一個圖像/ jpeg jax-rs提供程序類,爲我的基於後繼的Web服務創建一個圖像。我無法制定請求以測試以下內容,測試此方法的最簡單方法是什麼?創建JAX-RS提供程序從InputStream創建一個Java圖像

@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."); 
    } 
} 

回答

3

如果您的提供商也實現MessageBodyWriter,您可以使用客戶端庫(如Wink Client),並使用相同的供應商sennd圖像:

示例代碼表情:

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以獲得正確的媒體類型和類。