에서 pdf를 다운로드하려고합니다. 응답의 일부로 첨부하는 대신 응답 스트림의 일부인 URL에서 pdf를 다운로드하려고합니다. 아래에 코드를 시도했지만 거기에 많은 HTML 코드가 있기 때문에 pdf가 손상되면 많은 행운이 없습니다. 문제가있는 곳을 잘 모릅니다.URL 다운로드
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
System.out.println("resp: "+responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[1024*1024];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
어떤 도움을 주시면 감사하겠습니다. 고맙습니다.
코드이 튜토리얼이 완전히 작동 확인 및 이해하기 쉽습니다. https://androidknowledgeblog.wordpress.com/2016/04/02/download-pdf-from-server-android/ –