后端:
public void qryPdfInfo(HttpServletResponse response) {
// 实例化对象
HttpClient client = new HttpClient();
GetMethod get = null;
OutputStream output = null;
try {
List<Header> headers = new ArrayList<>();
// 第三方接口请求头
headers.add(new Header("Cookie", cookie));
get = new GetMethod("第三方接口请求url");
client.getHostConfiguration().getParams().setParameter(
"http.default-headers", headers);
if (200 == client.executeMethod(get)) {
output = response.getOutputStream();
byte[] responseBody = get.getResponseBody();
output.write(responseBody);
output.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关流
try {
if(output != null){
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
get.releaseConnection();
client.getHttpConnectionManager().closeIdleConnections(0);
}
}
前端JS:
使用ajax请求打开的pdf是空白的,这里采用xhr
var url = "本地接口url";
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.responseType = "blob"; // 返回类型blob
xhr.onload = function () {
// this.response 是返回的流数据
var blob = new Blob([this.response], {
type: 'application/pdf;chartset=UTF-8'
})
var fileURL= URL.createObjectURL(blob)
$("#pdf").attr("src", fileURL)
window.open(fileURL)
};
xhr.send()
前端页面:
在页面中加入pdf标签
<pdf id="pdf"></pdf>