Java에서 HttpResponse를 사용하여 다운로드를 처리하는 방법은 무엇입니까? 특정 사이트에 HttpGet 요청을했습니다. 사이트에서 다운로드 할 파일을 반환합니다. 이 다운로드를 어떻게 처리 할 수 있습니까? InputStream이 그것을 처리 할 수없는 것 같습니다 (아니면 내가 잘못된 방법으로 사용하고 있습니다).Java에서 핸들링
6
A
답변
8
를, 여기 SSCCE입니다 :
package com.stackoverflow.q2633002;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class Test {
public static void main(String... args) throws IOException {
System.out.println("Connecting...");
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://apache.cyberuse.com/httpcomponents/httpclient/binary/httpcomponents-client-4.0.1-bin.zip");
HttpResponse response = client.execute(get);
InputStream input = null;
OutputStream output = null;
byte[] buffer = new byte[1024];
try {
System.out.println("Downloading file...");
input = response.getEntity().getContent();
output = new FileOutputStream("/tmp/httpcomponents-client-4.0.1-bin.zip");
for (int length; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
System.out.println("File successfully downloaded!");
} finally {
if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
}
}
}
여기에 잘 작동합니다. 너의 문제는 다른 곳에있다.
+0
헤더 (Application/octet-stream)에 콘텐츠 유형을 추가하고 트릭을하는 것처럼 보이는 동일한 방법을 사용했습니다. – Tereno
0
일반적으로 브라우저에 다운로드 할 파일의 다운로드 대화 상자가 표시되도록하려면 들어오는 inputstream
콘텐츠를 응답 개체 스팀에 직접 설정하고 응답의 콘텐츠 형식 (HttpServletResponse
개체)을 관련 파일 형식으로 설정합니다.
즉
response.setContentType(.. relevant content type)
콘텐츠 유형은 예로서, PDF 파일 application/pdf
수있다.
브라우저에 브라우저 창에 관련 파일을 표시하는 플러그인이 있으면 파일이 열리고 사용자가 저장할 수 있습니다. 그렇지 않으면 브라우저에 다운로드 상자가 표시됩니다.
1
열기 스트림 및 파일 전송 : 당신은 실제로 약 HttpClient을 이야기하고 가정
try {
FileInputStream is = new FileInputStream(_backupDirectory + filename);
OutputStream os = response.getOutputStream();
byte[] buffer = new byte[65536];
int numRead;
while ((numRead = is.read(buffer, 0, buffer.length)) != -1) {
os.write(buffer, 0, numRead);
}
os.close();
is.close();
}
catch (FileNotFoundException fnfe) {
System.out.println("File " + filename + " not found");
}
무슨 API/라이브러리에 대해 이야기하고 있습니까? [Apache HttpComponents HttpClient v4] (http://hc.apache.org/httpcomponents-client/index.html)? 모르는 경우에는 'HttpResponse' 및 HttpGet 클래스의 패키지 이름을 언급하고 실수로 [SSCCE] (http://sscce.org)를 게시하여 실수를 발견 할 수 있도록하십시오. . – BalusC
실제로 Apache HttpComponents를 사용하고 있습니다. 당신이 게시 한 답변이 내가 원하는 것 같습니다. 그러나 문자열을 실제 파일과 비교하여 모든 입력을 저장할 수 있습니까? 입력 스트림을 문자열 메소드로 변환하면 버퍼링 된 판독기가 사용되지만 null이됩니다. – Tereno