Image Proxy using Jersey and HttpClient


Here’s the Jersey Endpoint:

    @GET
    @Path("imageproxy")
    @Produces("image/png")
    public Response imageproxy(@QueryParam("url") String url) {
        byte[] result = null;
        try {
             result = ImageHelper.getUrlBinary(url);
        } catch(Exception ex) {
            logger.error("Error proxying image", ex);
        }
        if(result != null) {
            return Response.ok(new ByteArrayInputStream(result)).build();
        } else {
            return Response.noContent().build();
        }
    }

Here’s the HttpClient code:

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;
import java.net.URI;

public class ImageHelper {
    private static Logger logger = Logger.getLogger(ImageHelper.class);
    public static byte[] getUrlBinary(String url) {
        byte[] result = null;
        try {
            URI uri = new URI(url);
            HttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(uri);
            HttpResponse response = client.execute(httpGet);
            result = IOUtils.toByteArray(response.getEntity().getContent());
        } catch(Exception ex) {
            logger.error("Error getting binary from: " + url, ex);
        }
        return result;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s