有些文章不一定是为了上首页投稿

Java接口对接三(URL方式之pdf,doc,excel等流文

2018-07-10  本文已影响58人  HaleyLiu

HttpClient 除了能传输xml , json ,form数据以外还可以传输pdf,doc,excel等文件流。

文件头对照表可以到这里去找:
http://tool.oschina.net/commons

1.先创建http工具类(CloseableHttpClient)

(1)二进制流不知道下载类型时可以用application/octet-stream
(2)若是pdf可以换成application-pdf
(3)若是word可换成 application/msword(对应doc文件)

 public static InputStream postStream(String url,String data){
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-type",ContentType.APPLICATION_OCTET_STREAM.toString());
        InputStream inputStream = null;
        try{
            StringEntity entity = new StringEntity(data);
            post.setEntity(entity);
            CloseableHttpResponse response = client.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode==200){
                Log.info("远程调用成功.line={}",response.getStatusLine());
                HttpEntity responseEntity = response.getEntity();
                inputStream =  responseEntity.getContent();
                return  inputStream;
            }
        }catch (Exception e){
            Log.error("远程调用失败.e={}",e.getMessage());
            return  inputStream;
        }
        return  inputStream;

    }

2.然后将流write到浏览器(这里以pdf为例)

@RequestMapping("/clientToPdf")
public void clientToPdf(HttpServletRequest request, HttpServletResponse response) throws IOException {
        BufferedInputStream buf = null;
        OutputStream out = null;
        try{
            InputStream in = HttpUtils.postStream("http://www.baidu.com","");//body为获取的pdf
            response.setContentType("application/pdf;charset=utf-8");
            out = response.getOutputStream();
            buf = new BufferedInputStream(in);
            int readBytes = 0;
            while ((readBytes = buf.read()) != -1) {
                out.write(readBytes);
            }
        } catch (Exception e) {
            LOGGER.info("文件获取异常");
        }finally {
            if (out != null) {
                out.close();
            }
            if (buf != null) {
                buf.close();
            }
        }

}
上一篇 下一篇

猜你喜欢

热点阅读