Java で HttpResponse を使用してダウンロードを処理するにはどうすればよいですか? 特定のサイトに HttpGet リクエストを送信しました。サイトはダウンロードするファイルを返します。このダウンロードを処理するにはどうすればよいですか? InputStream はそれを処理できないようです (または、間違った方法で使用している可能性があります)。
6400 次
3 に答える
8
実際にHttpClientについて話していると仮定すると、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) {}
}
}
}
ここでうまく動作します。あなたの問題は別の場所にあります。
于 2010-04-13T21:02:52.327 に答える
1
ストリームを開き、ファイルを送信します。
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" );
}
于 2010-04-13T20:44:16.587 に答える
0
一般に、ダウンロードするファイルのダウンロードダイアログボックスをブラウザに表示する場合は、受信inputstream
コンテンツを直接応答オブジェクトSteamに設定し、応答のコンテンツタイプ(HttpServletResponse
オブジェクト)を関連するファイルタイプに設定する必要があります。
すなわち、
response.setContentType(.. relevant content type)
例として、コンテンツタイプはapplication/pdf
PDFファイル用にすることができます。
ブラウザに関連ファイルをブラウザウィンドウに表示するプラグインがある場合、ファイルが開き、ユーザーは保存できます。そうでない場合、ブラウザはダウンロードボックスを表示します。
于 2010-04-13T20:41:09.683 に答える