java使用Okhttp请求pdf文档或图片(浏览器直接访问不下载)

最近遇到一个需求是用http方式请求nginx或者其他的web服务器映射的文件或图片,最开始一直返回的一串String字符串,最终经过多方测试调试调用http返回了流,将流转换成byte数组,然后直接通过OutputStream的write就可以浏览器直接查看不下载了。

// service业务方法
public byte[] picturefileProxy(HttpServletResponse response) {
    OKHttpUtil okHttpUtil = new OKHttpUtil();
     StringBuffer httpAddress = new StringBuffer("http://126.10.2.34:8088/file/8c3bdf75-12fa-4dbb-b8ac-dce82cc08e2a.pdf");//服务地址
      if (httpAddress.length() > 0) {
            // 获取服务地址后缀
            if (httpAddress.toString().contains(".")) {
                String hz = httpAddress.toString().substring(httpAddress.lastIndexOf("."), httpAddress.toString().length());
                //  response.setContentType 此步骤很重要,如果不添加则意味着直接下载,不能浏览器查看了,不同的请求,如pdf,图片什么的采用不同的Content
                if (hz.equals(".pdf")) {
                    response.setContentType("application/pdf");
                    // word
                } else if (hz.equals(".docx")) {
                    response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                } else if( hz.equals(".doc")){
                    response.setContentType("application/msword");
                }else if (hz.equals(".png") || hz.equals(".jpeg")
                        || hz.equals(".jpg") || hz.equals(".jpe")) {
                    response.setContentType("image/" + hz.replace(".", ""));
                } else if (hz.equals(".xls")) {
                    response.setContentType("application/vnd.ms-excel");
                }
            }
            bytes = okHttpUtil.sendGetForFile(httpAddress.toString());
        }
    return bytes;
}
 
// okhttp工具类
/**
     * Get获取文件数组请求
     *
     * @param url
     * @return
     */
    public final static byte[] sendGetForFile(String url) {
        InputStream inputStream = null;
        Request req = (new Request.Builder()).url(url).get().build();
        Response response = null;
        try {
            response = new OkHttpClient().newCall(req).execute();
            if (!response.isSuccessful()) {
                logger.error("【调用HTTP请求异常】 code:{},message:{}", response.code(), response.message());
                return null;
            }
            inputStream = response.body().byteStream();
            return inputToByte(inputStream);
        } catch (IOException e) {
            return null;
        } finally {
            try {
                inputStream.close();
            } catch (IOException var12) {
            }
        }
    }
得到的流转换为byte[]
    /**
     * 流转byte数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    private static byte[] inputToByte(InputStream inputStream) throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int rc;
        while ((rc = inputStream.read(buff, 0, 1024)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }
controller接收byte[]数组传递到response里
 @GetMapping("/picturefile/proxy/{resourceIdenti}")
    @ResponseBody
    public void picturefileProxy(@PathVariable(name = "resourceIdenti") String resourceIdenti,
                                 HttpServletResponse response) {
        byte[] bytes = proxyService.picturefileProxy(resourceIdenti, response);
        log.info("ContentType的格式:{}", response.getContentType());
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            os.write(bytes);
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

以上就是自己总结利用http方式调用其他http服务器浏览器观看ftp和图片不下载形式,希望可以帮助你,亲测可用

猜你喜欢

转载自blog.csdn.net/dfBeautifulLive/article/details/103514970