接口返回图片

来源:互联网 发布:java自带的乘法函数 编辑:程序博客网 时间:2024/06/06 07:37

场景:第三方需要取图片还有一些文件信息,需要这边制作一个接口服务返回数据。文件服务器、接口服务、第三方的应用(简称应用)都部署在内网,但应用因为通过一系列的网络处理,是可以外网访问的。接口服务和文件服务器只能内网访问。

注意:该方法是直接返回一张图片在浏览器中打开,而不是以附件的形式让用户下载

接口服务:

package cn.do1shoje.news;import java.util.List;import org.springframework.http.HttpHeaders;import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import cn.do1shoje.common.ImageUtil;@RestController@RequestMapping(value="/zxc")public class Test2 {@GetMapping("/cc/abc/{imgName}.{type}")public ResponseEntity cc(@PathVariable(value="imgName", required=true) String imgName,@PathVariable(value="type",required=true) String type) {HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.IMAGE_JPEG);//String url = "http://pic1.win4000.com/wallpaper/e/"+imgName+"."+type;String url = "http://img2.3lian.com/img2007/14/10/"+imgName+"."+type;byte []b = ImageUtil.getImage(url);ResponseEntity e = new ResponseEntity(b, headers, HttpStatus.CREATED);return e;}}

package cn.do1shoje.common;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.HttpClientBuilder;import org.apache.http.util.EntityUtils;public class ImageUtil {public static byte[] getImage(String url) {// TODO Auto-generated method stubHttpClient c = HttpClientBuilder.create().build();//"http://pic1.win4000.com/wallpaper/e/526c9f87129d9.jpg"HttpGet g = new HttpGet(url);HttpEntity entity = null;try {HttpResponse r = c.execute(g);entity = r.getEntity();byte [] b=EntityUtils.toByteArray(entity);return b;} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();return null;}}}



这里我们假设

http://pic1.win4000.com/wallpaper/e/526c9f87129d9.jpg和

http://img2.3lian.com/img2007/14/10/20080405111705577.png

是我们内网文件服务器的图片地址,我们先来看最终的结果,

浏览器输入http://127.0.0.1:8080/zxc/cc/abc/20080405111705577.png

结果如下:

我们可以看到,请求该接口服务的地址直接返回一张JPG格式的图片,而不是下载一张图片,这里之所以给出2个不同的地址,是因为同一地址下找不到不同格式的图片,所以网上随便找了下,真实环境一般主机ip都是固定的,只是文件的路径不一样而已,针对这种情况,完全可以用@PathVarizble路径变量注解来解决,所以这里就不演示这种方法了,这里只是拿了文件名来匹配,没匹配路径,还有需要注意的是,从文件服务器抓图片的时候,建议不要用Java自带的HttpUrlConnection,不要问我为什么,反正我弄了很久都没有成功。淡淡的忧桑。这里是用ApacheHttpClient来实现的,简单方便又高效,何乐而不为。如何你的项目是用Maven构建的,只需加个依赖即可:

<dependency>    <groupId>org.apache.httpcomponents</groupId>    <artifactId>httpclient</artifactId>    <version>4.5.3</version></dependency>



然后我们来研究研究源码:

Class:EntityUtil
public static byte[] toByteArray(final HttpEntity entity) throws IOException {        Args.notNull(entity, "Entity");        final InputStream instream = entity.getContent();        if (instream == null) {            return null;        }        try {            Args.check(entity.getContentLength() <= Integer.MAX_VALUE,                    "HTTP entity too large to be buffered in memory");            int capacity = (int)entity.getContentLength();            if (capacity < 0) {                capacity = DEFAULT_BUFFER_SIZE;            }            final ByteArrayBuffer buffer = new ByteArrayBuffer(capacity);            final byte[] tmp = new byte[DEFAULT_BUFFER_SIZE];            int l;            while((l = instream.read(tmp)) != -1) {                buffer.append(tmp, 0, l);            }            return buffer.toByteArray();        } finally {            instream.close();        }    }

Class:ByteArrayBuffer

public final class ByteArrayBuffer implements Serializable {    private static final long serialVersionUID = 4359112959524048036L;    private byte[] buffer;    private int len;    /**     * Creates an instance of {@link ByteArrayBuffer} with the given initial     * capacity.     *     * @param capacity the capacity     */    public ByteArrayBuffer(final int capacity) {        super();        Args.notNegative(capacity, "Buffer capacity");        this.buffer = new byte[capacity];    }    private void expand(final int newlen) {        final byte newbuffer[] = new byte[Math.max(this.buffer.length << 1, newlen)];        System.arraycopy(this.buffer, 0, newbuffer, 0, this.len);        this.buffer = newbuffer;    }    /**     * Appends {@code len} bytes to this buffer from the given source     * array starting at index {@code off}. The capacity of the buffer     * is increased, if necessary, to accommodate all {@code len} bytes.     *     * @param   b        the bytes to be appended.     * @param   off      the index of the first byte to append.     * @param   len      the number of bytes to append.     * @throws IndexOutOfBoundsException if {@code off} if out of     * range, {@code len} is negative, or     * {@code off} + {@code len} is out of range.     */    public void append(final byte[] b, final int off, final int len) {        if (b == null) {            return;        }        if ((off < 0) || (off > b.length) || (len < 0) ||                ((off + len) < 0) || ((off + len) > b.length)) {            throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length);        }        if (len == 0) {            return;        }        final int newlen = this.len + len;        if (newlen > this.buffer.length) {            expand(newlen);        }        System.arraycopy(b, off, this.buffer, this.len, len);        this.len = newlen;    }    /**     * Appends {@code b} byte to this buffer. The capacity of the buffer     * is increased, if necessary, to accommodate the additional byte.     *     * @param   b        the byte to be appended.     */    public void append(final int b) {        final int newlen = this.len + 1;        if (newlen > this.buffer.length) {            expand(newlen);        }        this.buffer[this.len] = (byte)b;        this.len = newlen;    }    /**     * Appends {@code len} chars to this buffer from the given source     * array starting at index {@code off}. The capacity of the buffer     * is increased if necessary to accommodate all {@code len} chars.     * <p>     * The chars are converted to bytes using simple cast.     *     * @param   b        the chars to be appended.     * @param   off      the index of the first char to append.     * @param   len      the number of bytes to append.     * @throws IndexOutOfBoundsException if {@code off} if out of     * range, {@code len} is negative, or     * {@code off} + {@code len} is out of range.     */    public void append(final char[] b, final int off, final int len) {        if (b == null) {            return;        }        if ((off < 0) || (off > b.length) || (len < 0) ||                ((off + len) < 0) || ((off + len) > b.length)) {            throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length);        }        if (len == 0) {            return;        }        final int oldlen = this.len;        final int newlen = oldlen + len;        if (newlen > this.buffer.length) {            expand(newlen);        }        for (int i1 = off, i2 = oldlen; i2 < newlen; i1++, i2++) {            this.buffer[i2] = (byte) b[i1];        }        this.len = newlen;    }    /**     * Appends {@code len} chars to this buffer from the given source     * char array buffer starting at index {@code off}. The capacity     * of the buffer is increased if necessary to accommodate all     * {@code len} chars.     * <p>     * The chars are converted to bytes using simple cast.     *     * @param   b        the chars to be appended.     * @param   off      the index of the first char to append.     * @param   len      the number of bytes to append.     * @throws IndexOutOfBoundsException if {@code off} if out of     * range, {@code len} is negative, or     * {@code off} + {@code len} is out of range.     */    public void append(final CharArrayBuffer b, final int off, final int len) {        if (b == null) {            return;        }        append(b.buffer(), off, len);    }    /**     * Clears content of the buffer. The underlying byte array is not resized.     */    public void clear() {        this.len = 0;    }    /**     * Converts the content of this buffer to an array of bytes.     *     * @return byte array     */    public byte[] toByteArray() {        final byte[] b = new byte[this.len];        if (this.len > 0) {            System.arraycopy(this.buffer, 0, b, 0, this.len);        }        return b;    }    /**     * Returns the {@code byte} value in this buffer at the specified     * index. The index argument must be greater than or equal to     * {@code 0}, and less than the length of this buffer.     *     * @param      i   the index of the desired byte value.     * @return     the byte value at the specified index.     * @throws     IndexOutOfBoundsException  if {@code index} is     *             negative or greater than or equal to {@link #length()}.     */    public int byteAt(final int i) {        return this.buffer[i];    }    /**     * Returns the current capacity. The capacity is the amount of storage     * available for newly appended bytes, beyond which an allocation     * will occur.     *     * @return  the current capacity     */    public int capacity() {        return this.buffer.length;    }    /**     * Returns the length of the buffer (byte count).     *     * @return  the length of the buffer     */    public int length() {        return this.len;    }    /**     * Ensures that the capacity is at least equal to the specified minimum.     * If the current capacity is less than the argument, then a new internal     * array is allocated with greater capacity. If the {@code required}     * argument is non-positive, this method takes no action.     *     * @param   required   the minimum required capacity.     *     * @since 4.1     */    public void ensureCapacity(final int required) {        if (required <= 0) {            return;        }        final int available = this.buffer.length - this.len;        if (required > available) {            expand(this.len + required);        }    }    /**     * Returns reference to the underlying byte array.     *     * @return the byte array.     */    public byte[] buffer() {        return this.buffer;    }    /**     * Sets the length of the buffer. The new length value is expected to be     * less than the current capacity and greater than or equal to     * {@code 0}.     *     * @param      len   the new length     * @throws     IndexOutOfBoundsException  if the     *               {@code len} argument is greater than the current     *               capacity of the buffer or less than {@code 0}.     */    public void setLength(final int len) {        if (len < 0 || len > this.buffer.length) {            throw new IndexOutOfBoundsException("len: "+len+" < 0 or > buffer len: "+this.buffer.length);        }        this.len = len;    }    /**     * Returns {@code true} if this buffer is empty, that is, its     * {@link #length()} is equal to {@code 0}.     * @return {@code true} if this buffer is empty, {@code false}     *   otherwise.     */    public boolean isEmpty() {        return this.len == 0;    }    /**     * Returns {@code true} if this buffer is full, that is, its     * {@link #length()} is equal to its {@link #capacity()}.     * @return {@code true} if this buffer is full, {@code false}     *   otherwise.     */    public boolean isFull() {        return this.len == this.buffer.length;    }    /**     * Returns the index within this buffer of the first occurrence of the     * specified byte, starting the search at the specified     * {@code beginIndex} and finishing at {@code endIndex}.     * If no such byte occurs in this buffer within the specified bounds,     * {@code -1} is returned.     * <p>     * There is no restriction on the value of {@code beginIndex} and     * {@code endIndex}. If {@code beginIndex} is negative,     * it has the same effect as if it were zero. If {@code endIndex} is     * greater than {@link #length()}, it has the same effect as if it were     * {@link #length()}. If the {@code beginIndex} is greater than     * the {@code endIndex}, {@code -1} is returned.     *     * @param   b            the byte to search for.     * @param   from         the index to start the search from.     * @param   to           the index to finish the search at.     * @return  the index of the first occurrence of the byte in the buffer     *   within the given bounds, or {@code -1} if the byte does     *   not occur.     *     * @since 4.1     */    public int indexOf(final byte b, final int from, final int to) {        int beginIndex = from;        if (beginIndex < 0) {            beginIndex = 0;        }        int endIndex = to;        if (endIndex > this.len) {            endIndex = this.len;        }        if (beginIndex > endIndex) {            return -1;        }        for (int i = beginIndex; i < endIndex; i++) {            if (this.buffer[i] == b) {                return i;            }        }        return -1;    }    /**     * Returns the index within this buffer of the first occurrence of the     * specified byte, starting the search at {@code 0} and finishing     * at {@link #length()}. If no such byte occurs in this buffer within     * those bounds, {@code -1} is returned.     *     * @param   b   the byte to search for.     * @return  the index of the first occurrence of the byte in the     *   buffer, or {@code -1} if the byte does not occur.     *     * @since 4.1     */    public int indexOf(final byte b) {        return indexOf(b, 0, this.len);    }}


 
原创粉丝点击