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

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();

}

}

}

Logo

电商企业物流数字化转型必备!快递鸟 API 接口,72 小时快速完成物流系统集成。全流程实战1V1指导,营造开放的API技术生态圈。

更多推荐