我编写此代码以从URL获取和下载PDF并写入OutputStream。但对于某些URL,PDF不能完全下载,下载的PDF只有6KB,我无法在PC上打开此PDF。
String strUrl = (request.getScheme() + "://" + request.getHeader("host") + request.getRequestURI() + "?" + request.getQueryString()).replace("?null", "").replace("%2F", "/");
URL url = new URL(java.net.URLDecoder.decode(strUrl, "UTF-8"));
System.out.println("URL ============= " + url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
conn.setRequestMethod(request.getMethod());
conn.connect();
InputStream is2 = conn.getInputStream();
System.out.println("---------- is2.available() ----------- "+is2.available());//NOTE : why Print 2?!!
OutputStream oos = response.getOutputStream();
if (url.toString().endsWith(".pdf")) {
response.setHeader("Content-type", "multipart/form-data");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"test.pdf\"");
System.out.println("dl" + rndPdfName + ".pdf");
}
byte[] buf = new byte[102400];
int c = 0;
while ((c = is2.read(buf, 0, buf.length)) > 0) {
oos.write(buf, 0, c);
if (url.toString().endsWith(".pdf")) {
oos.flush();
}
System.out.println("===> buf" + c + " ===> " + buf);//NOTE: just print 2 buf!!!!
}
if (url.toString().endsWith(".pdf")) {
oos.close();
is2.close();
}