創(chuàng)建httpclient 請(qǐng)求,并在header攜帶指定key,也可根據(jù)實(shí)際需要攜帶token等信息。獲取第三方接口返回的文件輸入流并寫到本地response中,實(shí)現(xiàn)返回文件流,前端通過js的a標(biāo)簽進(jìn)行下載。
代碼如下:文章來源:http://www.zghlxwxcb.cn/news/detail-588633.html
@Override
public void YKDownload(String fileId, HttpServletResponse response, HttpServletRequest request) {
logger.info("下載盈科附件, 參數(shù):附件id = " + fileId);
// 創(chuàng)建默認(rèn)的httpClient實(shí)例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 創(chuàng)建httpGet
HttpGet httpGet = new HttpGet("xxxxx" + fileId);
try {
// 設(shè)置請(qǐng)求頭參數(shù)
httpGet.setHeader("xxxx-Key", "xxxxxx");
CloseableHttpResponse httpResponse = httpclient.execute(httpGet);
// 獲取第三方接口放在Response中的文件名
Header[] headers = httpResponse.getHeaders("content-disposition");
if (headers != null && headers.length > 0) {
String contentDispositionValue = headers[0].getValue();
// 設(shè)置文件名,這里沒用加密文件名,可以自己設(shè)置
response.addHeader("Content-Disposition", contentDispositionValue);
}
response.setContentType("application/octet-stream;charset=utf-8");
HttpEntity entity = httpResponse.getEntity();
InputStream inputStream = entity.getContent(); //獲取輸入流
// 保存流 從這里到重置游標(biāo)
// 附件第一次下載沒問題再下載有時(shí)候就報(bào)錯(cuò),然后參照其他博主的方法,將流先保存下來
ByteArrayOutputStream bos = new ByteArrayOutputStream();
BufferedInputStream br = new BufferedInputStream(inputStream);
byte[] b = new byte[1024];
for (int c = 0; (c = br.read(b)) != -1;)
{
bos.write(b, 0, c);
}
b = null;
br.close();
inputStream = new ByteArrayInputStream(bos.toByteArray());
// 第一次讀流
StringBuffer out = new StringBuffer();
byte[] b1 = new byte[1024];
for (int n; (n = inputStream.read(b1)) != -1;) {
out.append(new String(b1, 0, n)); //這個(gè)可以用來讀取文件內(nèi)容 并且文件內(nèi)容有中文讀取出來也不會(huì)亂碼
}
// 判斷文件是否存在
String resultHtml = out.toString();
int firstIndex = resultHtml.indexOf("\n");
if(firstIndex < 0){
logger.info("文件不存在或異常"+resultHtml);
}
// 重置游標(biāo)
inputStream.reset();
// 輸出文件
ServletOutputStream outputStream = response.getOutputStream();
try {
byte[] oBuff = new byte[1024];
int iSize;
while (-1 != (iSize = inputStream.read(oBuff))) {
outputStream.write(oBuff, 0, iSize);
}
outputStream.flush();
} finally {
IOUtils.close(outputStream);
IOUtils.close(inputStream);
}
outputStream.close();
} catch (Exception e) {
logger.info("下載盈科附件, 原因:" + e.getMessage());
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
前端js代碼文章來源地址http://www.zghlxwxcb.cn/news/detail-588633.html
function fileYKDownload(fileId, fileName) {
//創(chuàng)建XMLHttpRequest對(duì)象
var httpRequest = new XMLHttpRequest();
//打開連接,將請(qǐng)求參數(shù)拼在url后面
httpRequest.open('GET', __baseUrl + '/v3/query/accessories/download?fileId=' + fileId, true);
//設(shè)置期望的返回值類型
httpRequest.responseType = "blob";
//設(shè)置請(qǐng)求頭,將認(rèn)證信息放入請(qǐng)求頭中
httpRequest.setRequestHeader("PRIVATETOKEN",$.getCookie(__token));
//請(qǐng)求成功回調(diào)函數(shù)
httpRequest.onload = function (oEvent) {
if (httpRequest.status === 200) {
// 這里文件名可以從response中獲取,為了方便我直接js方法傳的文件名
// var fileName = decodeURI(httpRequest.getResponseHeader("Content-Disposition"));
console.log(fileName);
var response = httpRequest.response;
//數(shù)據(jù)轉(zhuǎn)換為文件下載
var elink = document.createElement('a');
elink.download = fileName;
elink.style.display = 'none';
var blob = new Blob([response]);
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
document.body.removeChild(elink);
}
}
//發(fā)送請(qǐng)求
httpRequest.send();
}
到了這里,關(guān)于java通過httpclient攜帶請(qǐng)求頭參數(shù)獲取第三方文件流接口并實(shí)現(xiàn)實(shí)現(xiàn)文件下載的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!